<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/"><title>Analytics Drive - Algorithms &amp; Data Structures</title><link href="https://analyticsdrive.tech/" rel="alternate"/><link href="https://analyticsdrive.tech/feeds/algorithms-data-structures.atom.xml" rel="self"/><id>https://analyticsdrive.tech/</id><updated>2026-04-21T04:43:51.769467+05:30</updated><link href="https://pubsubhubbub.appspot.com/" rel="hub"/><entry><title>Trie Data Structures: Efficient Prefix Searching Explained</title><link href="https://analyticsdrive.tech/trie-data-structures-prefix-searching-explained/" rel="alternate"/><published>2026-03-25T17:02:00+05:30</published><updated>2026-03-25T17:02:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-25:/trie-data-structures-prefix-searching-explained/</id><summary type="html">&lt;p&gt;Explore Trie data structures for lightning-fast prefix searching, a core technique for applications like autocomplete, spell checkers, and efficient routing ...&lt;/p&gt;</summary><content type="html">&lt;p&gt;In the realm of computer science, optimizing operations on strings is a perennial challenge. From the predictive text on your smartphone to the lightning-fast search suggestions you receive online, the underlying mechanisms must be incredibly efficient. This is precisely where &lt;strong&gt;Trie Data Structures: Efficient Prefix Searching Explained&lt;/strong&gt; comes into play. A Trie, sometimes pronounced "tree" but more accurately "try" (derived from &lt;em&gt;retrieval&lt;/em&gt;), is a specialized tree-like data structure designed to store a dynamic set or associative array where the keys are usually strings. Its unique design enables extremely fast retrieval of keys based on prefixes, making it an indispensable tool for a wide array of applications that demand rapid prefix matching. Understanding its architecture and operational nuances is crucial for any developer looking to master advanced data structures and their practical applications.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-a-trie-data-structure"&gt;What is a Trie Data Structure?&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-fundamental-concept-prefix-based-organization"&gt;The Fundamental Concept: Prefix-Based Organization&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#how-trie-data-structures-facilitate-efficient-prefix-searching"&gt;How Trie Data Structures Facilitate Efficient Prefix Searching&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#trie-node-structure-the-building-blocks"&gt;Trie Node Structure: The Building Blocks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#insertion-operation-building-the-trie"&gt;Insertion Operation: Building the Trie&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#deletion-operation-removing-words-from-a-trie"&gt;Deletion Operation: Removing Words from a Trie&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#key-advantages-and-disadvantages-of-trie-data-structures"&gt;Key Advantages and Disadvantages of Trie Data Structures&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#advantages-swift-operations-and-lexicographical-order"&gt;Advantages: Swift Operations and Lexicographical Order&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#disadvantages-space-complexity-and-overhead"&gt;Disadvantages: Space Complexity and Overhead&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-complexity-analysis-a-deeper-dive"&gt;Time Complexity Analysis: A Deeper Dive&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity-the-trade-offs"&gt;Space Complexity: The Trade-offs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-trie-data-structures"&gt;Real-World Applications of Trie Data Structures&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#autocomplete-and-predictive-text"&gt;Autocomplete and Predictive Text&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#spell-checkers-and-dictionaries"&gt;Spell Checkers and Dictionaries&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ip-routing-longest-prefix-matching"&gt;IP Routing: Longest Prefix Matching&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#bioinformatics-dna-sequence-matching"&gt;Bioinformatics: DNA Sequence Matching&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#network-intrusion-detection-systems-nids"&gt;Network Intrusion Detection Systems (NIDS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#competitive-programming-and-algorithm-design"&gt;Competitive Programming and Algorithm Design&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#enhancing-search-engines-with-tries"&gt;Enhancing Search Engines with Tries&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#tries-in-data-compression-algorithms"&gt;Tries in Data Compression Algorithms&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#advanced-variations-and-optimizations"&gt;Advanced Variations and Optimizations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#radix-trees-patricia-tries"&gt;Radix Trees (Patricia Tries)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#ternary-search-trees-tsts"&gt;Ternary Search Trees (TSTs)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#suffix-tries"&gt;Suffix Tries&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#future-trends-and-the-evolving-role-of-tries"&gt;Future Trends and the Evolving Role of Tries&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="what-is-a-trie-data-structure"&gt;What is a Trie Data Structure?&lt;/h2&gt;
&lt;p&gt;A Trie, also known as a prefix tree, is a tree-like data structure used for storing a collection of strings. Unlike a &lt;a href="https://analyticsdrive.tech/binary-search-tree/"&gt;binary search tree&lt;/a&gt; (BST) where nodes store entire keys, each node in a Trie represents a common prefix of the strings being stored. The root of the Trie typically represents an empty string. As you traverse down from the root, each edge represents a character, and nodes further down represent longer prefixes. A key distinction is that not every node in a Trie necessarily marks the end of a valid word; only specific nodes are designated as such.&lt;/p&gt;
&lt;p&gt;Imagine a traditional dictionary. If you want to find all words starting with "comp," you'd manually scan through pages until you find "computer," "compress," "computation," and so on. A Trie automates this process by organizing words based on their shared initial characters, much like a hierarchical folder system where each folder name is a character and subfolders represent subsequent characters. This structure naturally groups words with common prefixes together, leading to exceptional performance for operations like prefix searching, auto-completion, and spell-checking.&lt;/p&gt;
&lt;p&gt;For example, consider storing the words "cat", "car", and "dog".&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The root would be empty.&lt;/li&gt;
&lt;li&gt;From the root, an edge 'c' leads to a node.&lt;/li&gt;
&lt;li&gt;From that node, an edge 'a' leads to another node.&lt;/li&gt;
&lt;li&gt;From that 'a' node, an edge 't' leads to a node marked as the end of "cat".&lt;/li&gt;
&lt;li&gt;Also from that 'a' node, an edge 'r' leads to a node marked as the end of "car".&lt;/li&gt;
&lt;li&gt;Separately, from the root, an edge 'd' leads to a node.&lt;/li&gt;
&lt;li&gt;From that node, an edge 'o' leads to another node.&lt;/li&gt;
&lt;li&gt;From that 'o' node, an edge 'g' leads to a node marked as the end of "dog".&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This structure allows for highly efficient traversal when searching for words or prefixes. When you search for "ca", you simply follow the 'c' edge, then the 'a' edge. All words reachable from this 'a' node will begin with "ca".&lt;/p&gt;
&lt;h3 id="the-fundamental-concept-prefix-based-organization"&gt;The Fundamental Concept: Prefix-Based Organization&lt;/h3&gt;
&lt;p&gt;The core idea behind a Trie's efficiency is its prefix-based organization. Each path from the root to a node represents a unique prefix. If a node is marked as the end of a word, it signifies that the string formed by traversing the path to that node is a complete word in the dictionary. If a node is not marked as the end of a word, it implies that the string formed by its path is merely a prefix to one or more longer words.&lt;/p&gt;
&lt;p&gt;This systematic arrangement provides several advantages over other data structures like hash tables or binary search trees when dealing with string data. Hash tables offer O(L) average time complexity for string operations, where L is the length of the string, but worst-case scenarios can degrade performance due to collisions. For a more in-depth understanding of hashing, read about &lt;a href="/what-is-a-hash-map-hashing-concepts/"&gt;What is a Hash Map? Deep Dive into Hashing Concepts Unveiled&lt;/a&gt;. Binary search trees, while providing O(L*logN) for operations (where N is the number of words), involve string comparisons at each node, which can be computationally expensive. Tries, by contrast, avoid string comparisons entirely during traversal; they simply follow character-based links. This character-by-character traversal is inherently faster for prefix-related tasks.&lt;/p&gt;
&lt;p&gt;Furthermore, a Trie inherently maintains lexicographical order of keys, which is a desirable property for many applications. When you traverse a Trie's children in alphabetical order, you automatically retrieve words in lexicographical order. This makes Tries a superior choice for scenarios where both quick prefix matching and sorted output are required. This organization method forms the bedrock of its impressive performance characteristics, particularly in scenarios demanding rapid prefix lookups and auto-completion.&lt;/p&gt;
&lt;h2 id="how-trie-data-structures-facilitate-efficient-prefix-searching"&gt;How Trie Data Structures Facilitate Efficient Prefix Searching&lt;/h2&gt;
&lt;p&gt;The true power of Trie data structures lies in their ability to perform prefix searches with unparalleled efficiency. When you initiate a prefix search, say for "app", the Trie traversal mirrors this sequence of characters. Starting from the root, you follow the edge labeled 'a' to its child node. From there, you follow the edge labeled 'p' to its child node. Finally, you follow another 'p' edge to its child. The node you arrive at after traversing "app" is the root of a sub-Trie containing all words that begin with "app". From this point, you can effortlessly collect all complete words within this sub-Trie, such as "apple", "apply", "application", etc.&lt;/p&gt;
&lt;p&gt;This sequential character matching, rather than full string comparisons, makes the search operation remarkably fast. The time complexity for searching a word or a prefix of length L is O(L), because in the worst case, you only need to traverse L nodes. This is significantly faster than hashing (which still needs to compute a hash for a string of length L) or tree-based comparisons (which might compare entire strings or large portions repeatedly). For applications like autocomplete, where users type characters one by one and expect instant suggestions, this O(L) complexity is critical. It guarantees that the response time scales directly with the length of the typed prefix, not the total number of words in the dictionary.&lt;/p&gt;
&lt;h3 id="trie-node-structure-the-building-blocks"&gt;Trie Node Structure: The Building Blocks&lt;/h3&gt;
&lt;p&gt;At the heart of every Trie is its node structure. Each node in a Trie is typically composed of two main components:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Children Pointers/Array:&lt;/strong&gt; This is an array or a hash map (dictionary) that points to the next level of nodes. The size of this array usually corresponds to the size of the alphabet being used (e.g., 26 for English lowercase letters, or 256 for ASCII characters). For example, &lt;code&gt;children[0]&lt;/code&gt; might point to the node representing 'a', &lt;code&gt;children[1]&lt;/code&gt; for 'b', and so on. If using a hash map, keys would be characters and values would be child nodes. Using a hash map is more space-efficient for sparse alphabets or very large character sets, as it only stores pointers for characters that actually exist in the Trie from that node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;isEndOfWord&lt;/code&gt; Flag (or equivalent):&lt;/strong&gt; A boolean flag, often named &lt;code&gt;isEndOfWord&lt;/code&gt;, &lt;code&gt;isLeaf&lt;/code&gt;, or &lt;code&gt;isCompleteWord&lt;/code&gt;, indicates whether the path from the root to the current node forms a complete, valid word in the stored set. If this flag is &lt;code&gt;true&lt;/code&gt;, it means the sequence of characters leading to this node represents a word that has been inserted into the Trie. For instance, in a Trie containing "apple" and "apply", the node reached after 'a', 'p', 'p', 'l', 'e' would have &lt;code&gt;isEndOfWord&lt;/code&gt; set to &lt;code&gt;true&lt;/code&gt;, as would the node reached after 'a', 'p', 'p', 'l', 'y'. The node reached after 'a', 'p', 'p' would likely have &lt;code&gt;isEndOfWord&lt;/code&gt; set to &lt;code&gt;false&lt;/code&gt;, unless "app" itself is also a valid word.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Here's a conceptual representation of a Trie node:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TrieNode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;children&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;  &lt;span class="c1"&gt;# Dictionary to store child nodes (character -&amp;gt; TrieNode)&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;is_end_of_word&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The choice between an array and a hash map for &lt;code&gt;children&lt;/code&gt; has significant implications for space and time complexity. An array provides O(1) access to children but can be very sparse and consume a lot of memory for larger alphabets. A hash map uses more memory per entry due to hashing overhead but is more memory-efficient when many child pointers are null, as it only allocates space for existing children.&lt;/p&gt;
&lt;h3 id="insertion-operation-building-the-trie"&gt;Insertion Operation: Building the Trie&lt;/h3&gt;
&lt;p&gt;Inserting a word into a Trie involves traversing the structure character by character. If a character's corresponding node doesn't exist along the path, a new node is created.&lt;/p&gt;
&lt;p&gt;Let's illustrate with an example. Suppose we want to insert the words "apple", "apply", and "apt":&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insert "apple":&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Start at the root.&lt;/li&gt;
&lt;li&gt;For 'a': Does a child node 'a' exist? No. Create a new node for 'a'. Move to this new node.&lt;/li&gt;
&lt;li&gt;For 'p': Does a child node 'p' exist? No. Create a new node for 'p'. Move to this new node.&lt;/li&gt;
&lt;li&gt;For 'p': Does a child node 'p' exist? No. Create a new node for 'p'. Move to this new node.&lt;/li&gt;
&lt;li&gt;For 'l': Does a child node 'l' exist? No. Create a new node for 'l'. Move to this new node.&lt;/li&gt;
&lt;li&gt;For 'e': Does a child node 'e' exist? No. Create a new node for 'e'. Move to this new node.&lt;/li&gt;
&lt;li&gt;End of word "apple". Mark the current node's &lt;code&gt;isEndOfWord&lt;/code&gt; as &lt;code&gt;true&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insert "apply":&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Start at the root.&lt;/li&gt;
&lt;li&gt;For 'a': Child node 'a' exists. Move to it.&lt;/li&gt;
&lt;li&gt;For 'p': Child node 'p' exists. Move to it.&lt;/li&gt;
&lt;li&gt;For 'p': Child node 'p' exists. Move to it.&lt;/li&gt;
&lt;li&gt;For 'l': Child node 'l' exists. Move to it.&lt;/li&gt;
&lt;li&gt;For 'y': Does a child node 'y' exist? No. Create a new node for 'y'. Move to this new node.&lt;/li&gt;
&lt;li&gt;End of word "apply". Mark the current node's &lt;code&gt;isEndOfWord&lt;/code&gt; as &lt;code&gt;true&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insert "apt":&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Start at the root.&lt;/li&gt;
&lt;li&gt;For 'a': Child node 'a' exists. Move to it.&lt;/li&gt;
&lt;li&gt;For 'p': Child node 'p' exists. Move to it.&lt;/li&gt;
&lt;li&gt;For 't': Does a child node 't' exist? No. Create a new node for 't'. Move to this new node.&lt;/li&gt;
&lt;li&gt;End of word "apt". Mark the current node's &lt;code&gt;isEndOfWord&lt;/code&gt; as &lt;code&gt;true&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The time complexity for insertion is O(L), where L is the length of the word being inserted. This is because, in the worst case, we traverse L nodes and potentially create L new nodes. This efficiency makes Tries highly suitable for dynamic dictionaries where words are frequently added.&lt;/p&gt;
&lt;h3 id="deletion-operation-removing-words-from-a-trie"&gt;Deletion Operation: Removing Words from a Trie&lt;/h3&gt;
&lt;p&gt;Deleting a word from a Trie is often more complex than insertion or searching, as simply removing nodes might inadvertently break paths for other words that share prefixes. A robust deletion algorithm usually involves a recursive approach that checks several conditions:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Is the word actually present?&lt;/strong&gt; First, perform a search to confirm the word exists. If not, there's nothing to delete.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark &lt;code&gt;isEndOfWord&lt;/code&gt; as &lt;code&gt;false&lt;/code&gt;:&lt;/strong&gt; If the word exists, the primary step is to mark the &lt;code&gt;isEndOfWord&lt;/code&gt; flag of the node corresponding to the last character of the word as &lt;code&gt;false&lt;/code&gt;. This effectively removes the word from the dictionary without altering the structure for shared prefixes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Check for removable nodes:&lt;/strong&gt; After unmarking &lt;code&gt;isEndOfWord&lt;/code&gt;, you can potentially remove nodes upwards from the end of the word, but only if they meet specific criteria:&lt;ul&gt;
&lt;li&gt;The node is no longer marked as &lt;code&gt;isEndOfWord&lt;/code&gt; (&lt;code&gt;isEndOfWord&lt;/code&gt; is &lt;code&gt;false&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;The node has no other children (i.e., it's not a prefix to any other word).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If both conditions are met, the node can be safely removed, and this process can be recursively applied to its parent. This ensures that shared prefixes are preserved while unique branches are pruned. This careful approach prevents unintentional deletion of prefixes or other words. The time complexity for deletion is also O(L), as it involves traversing the length of the word and potentially some back-tracking.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example for Deletion:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Consider a Trie with "apple", "apply", "app".
If we delete "apple":&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Find the node for 'e' in "apple".&lt;/li&gt;
&lt;li&gt;Set its &lt;code&gt;isEndOfWord&lt;/code&gt; to &lt;code&gt;false&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Now, check node 'e': it has no children, and &lt;code&gt;isEndOfWord&lt;/code&gt; is &lt;code&gt;false&lt;/code&gt;. So, it can be deleted. Remove the link from its parent 'l'.&lt;/li&gt;
&lt;li&gt;Check node 'l': its &lt;code&gt;isEndOfWord&lt;/code&gt; is &lt;code&gt;false&lt;/code&gt; (it's not "appl" as a word), and it now has no children. So, it can be deleted. Remove the link from its parent 'p'.&lt;/li&gt;
&lt;li&gt;Check the 'p' node (for "app"): its &lt;code&gt;isEndOfWord&lt;/code&gt; is &lt;code&gt;true&lt;/code&gt; (because "app" is a word), AND it has a child (leading to "apply"). So, this 'p' node cannot be deleted. The deletion stops here.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If "apple" was the only word inserted, and we delete "apple", then all nodes from 'e' back up to 'a' (or even the root if 'a' was not part of any other word) would be deleted. This careful process ensures data integrity within the Trie.&lt;/p&gt;
&lt;h2 id="key-advantages-and-disadvantages-of-trie-data-structures"&gt;Key Advantages and Disadvantages of Trie Data Structures&lt;/h2&gt;
&lt;p&gt;Trie data structures offer a compelling set of advantages, particularly for string-centric applications, but they also come with certain trade-offs that developers must consider.&lt;/p&gt;
&lt;h3 id="advantages-swift-operations-and-lexicographical-order"&gt;Advantages: Swift Operations and Lexicographical Order&lt;/h3&gt;
&lt;p&gt;The primary advantages of Tries include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Exceptional Performance for Prefix Operations:&lt;/strong&gt; As discussed, searching for a word, inserting a word, or finding all words with a given prefix can be done in O(L) time, where L is the length of the key. This makes Tries ideal for real-time applications like autocomplete, spell-checking, and dictionary lookup.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No Hash Collisions:&lt;/strong&gt; Unlike hash tables, Tries do not rely on hash functions, completely eliminating the possibility of hash collisions, which can degrade performance in worst-case scenarios for hash-based structures.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Lexicographical Ordering:&lt;/strong&gt; Tries inherently store keys in lexicographical (alphabetical) order. A simple depth-first traversal of the Trie will yield all stored words in sorted order, which is a desirable feature for many applications and comes "for free" with the Trie's structure.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficient Longest Prefix Matching:&lt;/strong&gt; For applications like IP routing, Tries can quickly find the longest matching prefix for a given key, which is crucial for determining the most specific route.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Space Optimization for Shared Prefixes:&lt;/strong&gt; When many words share common prefixes (e.g., "apple", "apply", "application"), the Trie structure allows these prefixes to be stored only once, potentially saving space compared to storing each word independently.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="disadvantages-space-complexity-and-overhead"&gt;Disadvantages: Space Complexity and Overhead&lt;/h3&gt;
&lt;p&gt;Despite their benefits, Tries also have notable drawbacks:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;High Space Consumption:&lt;/strong&gt; This is often the most significant disadvantage. Each node typically needs an array or hash map for its children. For large alphabets (e.g., Unicode characters) or sparse data (where many pointers would be null), this can lead to substantial memory usage. A node with 26 pointers for the English alphabet, even if most are null, can consume considerable memory.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory Fragmentation:&lt;/strong&gt; The dynamic creation of numerous small Trie nodes can lead to memory fragmentation, impacting performance in long-running systems.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Complex Deletion:&lt;/strong&gt; As explored, deleting words from a Trie is not trivial and requires careful recursive logic to avoid breaking other words or prefixes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not Ideal for Non-String Keys:&lt;/strong&gt; Tries are specifically designed for string keys (or sequences of characters/symbols). They are not well-suited for arbitrary numerical or complex object keys without prior conversion to a string representation.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Understanding these pros and cons is essential for determining whether a Trie is the most appropriate data structure for a given problem. While its O(L) time complexity for string operations is compelling, the space overhead can be a critical limiting factor, especially in memory-constrained environments.&lt;/p&gt;
&lt;h3 id="time-complexity-analysis-a-deeper-dive"&gt;Time Complexity Analysis: A Deeper Dive&lt;/h3&gt;
&lt;p&gt;Let's quantitatively compare the time complexities of core string operations for different data structures:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style="text-align: left;"&gt;Operation&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Trie&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Hash Table (avg)&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Hash Table (worst)&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Binary Search Tree (avg)&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Binary Search Tree (worst)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Search&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*N)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*logN)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*N)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Insert&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*N)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*logN)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*N)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Delete&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*N)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*logN)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*N)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Prefix Search&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L + K) where K is number of matched words&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Not directly supported efficiently&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Not directly supported efficiently&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*N)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(L*N)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;Legend:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;L:&lt;/strong&gt; Length of the key (string).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;N:&lt;/strong&gt; Number of keys/words in the data structure.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;K:&lt;/strong&gt; Number of words matching the prefix.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As the table clearly illustrates, Tries offer consistent O(L) performance for search, insert, and delete operations. This is because each step involves a simple character lookup and following a pointer, irrespective of the total number of words (N) in the Trie. For hash tables, while the average case is also O(L), the worst-case can degenerate to O(L*N) if there are many collisions or if the hash function is poor, requiring comparisons of all N strings in a bucket. Binary Search Trees, which rely on full string comparisons at each node, incur an O(L) cost for each comparison, leading to O(L*logN) on average and O(L*N) in the worst case (for an unbalanced tree). Critically, for prefix searching, Tries are vastly superior, offering an O(L+K) complexity to find all K words starting with a prefix of length L, whereas other structures would require iterating through all N words.&lt;/p&gt;
&lt;h3 id="space-complexity-the-trade-offs"&gt;Space Complexity: The Trade-offs&lt;/h3&gt;
&lt;p&gt;The space complexity of a Trie is highly dependent on the number of nodes, the size of the alphabet, and how dense the Trie is.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Worst Case:&lt;/strong&gt; In the worst-case scenario, if no two words share any common prefixes (e.g., "a", "b", "c", ..., "z"), then each character would create a new node, and the space complexity would be proportional to the sum of the lengths of all words (ΣL). Furthermore, each node has &lt;code&gt;alphabet_size&lt;/code&gt; pointers. So, &lt;code&gt;Space = (Total_Characters_in_Trie_Nodes) * (Size_of_Pointer_Array)&lt;/code&gt;. If using an array of pointers of size &lt;code&gt;A&lt;/code&gt; (alphabet size), and there are &lt;code&gt;M&lt;/code&gt; nodes, then the space is approximately &lt;code&gt;O(M * A)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Best Case (Shared Prefixes):&lt;/strong&gt; When words share many common prefixes, the space complexity can be significantly reduced. For example, storing "internationalization" and "interplanetary" will share the "inter" prefix nodes. The space is still &lt;code&gt;O(M * A)&lt;/code&gt;, but &lt;code&gt;M&lt;/code&gt; (number of nodes) would be much smaller than the sum of lengths if prefixes are shared.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To put this into perspective, consider storing 100,000 English words. If each node requires an array of 26 pointers, and a boolean flag, it can quickly add up to tens or hundreds of megabytes, even if many pointers are null. This overhead is a primary reason why specialized variants like Radix Tries were developed.&lt;/p&gt;
&lt;h2 id="real-world-applications-of-trie-data-structures"&gt;Real-World Applications of Trie Data Structures&lt;/h2&gt;
&lt;p&gt;Trie data structures are not merely academic curiosities; they are foundational to many everyday technologies we interact with. Their efficiency in prefix matching makes them indispensable across a variety of domains.&lt;/p&gt;
&lt;h3 id="autocomplete-and-predictive-text"&gt;Autocomplete and Predictive Text&lt;/h3&gt;
&lt;p&gt;Perhaps the most ubiquitous application of Tries is in autocomplete and predictive text features. Whether you're typing a search query into Google, composing an email, or texting on your smartphone, Tries are working behind the scenes. As you type each character, the system quickly traverses the Trie to the node representing the current prefix. From that node, it can efficiently enumerate all possible words that complete the prefix, presenting them as suggestions. This instantaneous feedback greatly enhances user experience and typing speed. Companies like Google heavily rely on optimized Trie variations to power their search suggestions, handling billions of queries with minimal latency. For another perspective on search optimization, consider &lt;a href="/understanding-vector-embeddings-ai-search-engines/"&gt;Understanding Vector Embeddings: Core of AI Search Engines&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id="spell-checkers-and-dictionaries"&gt;Spell Checkers and Dictionaries&lt;/h3&gt;
&lt;p&gt;Tries form the backbone of many spell-checking algorithms. When a user types a word, the spell checker can quickly search for it in a Trie populated with a vast dictionary. If the word is not found, the system can then leverage the Trie's prefix matching capabilities to suggest corrections. For instance, by exploring nearby paths (e.g., single character edits, transpositions), it can quickly find words that are "close" to the misspelled input. This not only speeds up the check but also improves the relevance of suggestions.&lt;/p&gt;
&lt;h3 id="ip-routing-longest-prefix-matching"&gt;IP Routing: Longest Prefix Matching&lt;/h3&gt;
&lt;p&gt;In computer networking, IP routers need to determine the optimal path for data packets. This involves matching the destination IP address of a packet against a routing table that contains network addresses and their corresponding gateways. A critical aspect here is "longest prefix matching." If an IP address matches multiple entries in the routing table (e.g., &lt;code&gt;192.168.1.0/24&lt;/code&gt; and &lt;code&gt;192.168.1.128/28&lt;/code&gt;), the router must choose the entry with the longest matching prefix (the most specific route). Tries, specifically a variant called a "Patricia Trie" or "Radix Tree," are highly efficient for this task. They allow routers to quickly traverse the tree based on the bits of the IP address, finding the longest matching prefix in O(L) time, where L is the length of the IP address (e.g., 32 bits for IPv4, 128 bits for IPv6).&lt;/p&gt;
&lt;h3 id="bioinformatics-dna-sequence-matching"&gt;Bioinformatics: DNA Sequence Matching&lt;/h3&gt;
&lt;p&gt;In bioinformatics, the analysis of DNA and RNA sequences involves finding patterns, identifying common subsequences, and aligning genomes. Tries and their advanced forms, like suffix trees and suffix arrays (which are built using suffix tries), are fundamental to these operations. By storing all suffixes of a large biological sequence in a Trie, researchers can quickly search for any pattern (subsequence) within that sequence, identify repeated regions, and perform complex comparisons crucial for genetic research and drug discovery.&lt;/p&gt;
&lt;h3 id="network-intrusion-detection-systems-nids"&gt;Network Intrusion Detection Systems (NIDS)&lt;/h3&gt;
&lt;p&gt;Tries are also employed in network intrusion detection systems. NIDS often need to inspect network packets for signatures of known attacks, which can be represented as sequences of bytes or specific string patterns. By loading these attack signatures into a Trie, the NIDS can rapidly scan incoming packet payloads. As each byte or character of the payload is processed, the system traverses the Trie. If a path leads to a node marked as an end of an attack signature, an alert can be triggered. This allows for high-speed pattern matching required for real-time threat detection.&lt;/p&gt;
&lt;h3 id="competitive-programming-and-algorithm-design"&gt;Competitive Programming and Algorithm Design&lt;/h3&gt;
&lt;p&gt;For competitive programmers and algorithm designers, Tries are a powerful tool for solving a wide array of string-related problems efficiently. They are frequently used in problems that involve:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Finding the maximum XOR pair in an array (using a binary Trie).&lt;/li&gt;
&lt;li&gt;Counting distinct substrings.&lt;/li&gt;
&lt;li&gt;Implementing custom dictionaries with fast lookups.&lt;/li&gt;
&lt;li&gt;Solving problems related to "k-th smallest string" or "longest common prefix."&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Their deterministic O(L) performance for many operations makes them a go-to choice when string manipulation efficiency is paramount. For insights into other efficient algorithmic approaches, explore &lt;a href="/dynamic-programming-breaking-down-complex-problems/"&gt;Dynamic Programming: Breaking Down Complex Problems Efficiently&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id="enhancing-search-engines-with-tries"&gt;Enhancing Search Engines with Tries&lt;/h3&gt;
&lt;p&gt;Beyond basic autocomplete, Tries play a deeper role in search engine architecture. When you type a query, the search engine doesn't just suggest popular terms; it often corrects misspellings or suggests related concepts. Tries can store not only keywords but also their relationships, synonyms, and common misspellings. This enables search engines to provide more intelligent and context-aware suggestions, significantly improving the user's search experience by guiding them to the most relevant results, even if their initial query is imperfect. The ability to quickly traverse common prefixes of millions or billions of indexed terms is fundamental to the speed and responsiveness of modern search interfaces.&lt;/p&gt;
&lt;h3 id="tries-in-data-compression-algorithms"&gt;Tries in Data Compression Algorithms&lt;/h3&gt;
&lt;p&gt;While not always directly called Tries, the underlying principles of prefix trees are central to several data compression algorithms. Huffman coding, for example, builds a binary tree (a type of Trie) where paths represent bit sequences and leaf nodes represent characters. More frequently occurring characters are assigned shorter bit sequences, forming a variable-length code. The entire encoding/decoding process relies on traversing this prefix tree. Lempel-Ziv-Welch (LZW) algorithm, used in GIF images and &lt;code&gt;compress&lt;/code&gt; utility, also implicitly uses a dictionary of strings (which can be conceptually represented as a Trie) to identify and encode repeating patterns, essentially representing longer sequences with shorter codes. The efficiency of prefix lookup is critical for building and using these compression dictionaries.&lt;/p&gt;
&lt;h2 id="advanced-variations-and-optimizations"&gt;Advanced Variations and Optimizations&lt;/h2&gt;
&lt;p&gt;The basic Trie structure, while powerful, has inspired several advanced variations and optimizations designed to address its limitations, primarily space consumption. These specialized Tries extend the core concept to handle more complex scenarios or achieve greater efficiency.&lt;/p&gt;
&lt;h3 id="radix-trees-patricia-tries"&gt;Radix Trees (Patricia Tries)&lt;/h3&gt;
&lt;p&gt;Radix trees, also known as Patricia Tries (Practical Algorithm to Retrieve Information Coded In Alphanumeric), are a significant optimization of the basic Trie. They are designed to save space by compressing paths that contain only nodes with a single child. Instead of having separate nodes for each character in a unique path, a Radix Tree combines multiple single-child nodes into a single edge, labeling that edge with the &lt;em&gt;entire string&lt;/em&gt; of characters it represents.&lt;/p&gt;
&lt;p&gt;For example, in a standard Trie, if you had words "tester" and "testing", the path from "test" would branch. If you had only "testing" and no other words starting with "testi", then 't', 'e', 's', 't', 'i', 'n', 'g' would each be separate nodes. In a Radix Tree, if "test" leads to 'i', and 'i' only leads to 'n', and 'n' only leads to 'g', then the path from the node representing "test" to the node representing "testing" could be represented by a single edge labeled "ing". This significantly reduces the number of nodes, making it more space-efficient, especially for sparse Tries or when keys have long unique suffixes. Radix trees are commonly used in IP routing tables due to their space efficiency and excellent performance for longest prefix matching.&lt;/p&gt;
&lt;h3 id="ternary-search-trees-tsts"&gt;Ternary Search Trees (TSTs)&lt;/h3&gt;
&lt;p&gt;Ternary Search Trees (TSTs) offer a space-efficient alternative to traditional Tries, especially when the alphabet size is large or the Trie is very sparse (i.e., many nodes have few children). Instead of an array or hash map for children, each node in a TST has at most three pointers:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;left&lt;/code&gt; child:&lt;/strong&gt; Points to a node whose character value is &lt;em&gt;less than&lt;/em&gt; the current node's character.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;middle&lt;/code&gt; child:&lt;/strong&gt; Points to a node representing the &lt;em&gt;next character&lt;/em&gt; in the current word.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;right&lt;/code&gt; child:&lt;/strong&gt; Points to a node whose character value is &lt;em&gt;greater than&lt;/em&gt; the current node's character.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When searching or inserting, you compare the current character of the key with the character at the current node:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the key character is less, go &lt;code&gt;left&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If the key character is greater, go &lt;code&gt;right&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If they match, go &lt;code&gt;middle&lt;/code&gt; (and advance to the next character in the key).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This structure combines aspects of binary search trees with Tries. While search operations might take slightly longer (average O(L + log A), where A is alphabet size, worst case O(L * A)), TSTs often consume much less memory than standard Tries, as they don't allocate large arrays for children at every node. They are particularly well-suited for dictionary implementations and problems where memory is a tighter constraint than raw speed.&lt;/p&gt;
&lt;h3 id="suffix-tries"&gt;Suffix Tries&lt;/h3&gt;
&lt;p&gt;A Suffix Trie is a specialized Trie that stores all possible suffixes of a given text. For a string &lt;code&gt;S&lt;/code&gt; of length &lt;code&gt;N&lt;/code&gt;, a suffix Trie would contain &lt;code&gt;N&lt;/code&gt; words: &lt;code&gt;S[0...N-1]&lt;/code&gt;, &lt;code&gt;S[1...N-1]&lt;/code&gt;, ..., &lt;code&gt;S[N-1...N-1]&lt;/code&gt;. Building a suffix Trie for a string of length &lt;code&gt;N&lt;/code&gt; can be done in O(N) time using advanced algorithms (like Ukkonen's algorithm), making it incredibly powerful for various string matching problems.&lt;/p&gt;
&lt;p&gt;Key applications of suffix Tries include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Pattern Searching:&lt;/strong&gt; Finding all occurrences of a pattern in a text quickly.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Longest Common Substring:&lt;/strong&gt; Identifying the longest string that is a substring of two or more given strings.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Finding Repeated Substrings:&lt;/strong&gt; Locating repeated sequences within a text.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DNA Sequence Analysis:&lt;/strong&gt; As mentioned in bioinformatics, suffix Tries are crucial for finding common patterns in large biological sequences.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;While building a suffix Trie can be complex, its ability to answer complex substring queries in O(L) time (where L is the pattern length) makes it an invaluable tool for specific types of algorithmic challenges.&lt;/p&gt;
&lt;h2 id="future-trends-and-the-evolving-role-of-tries"&gt;Future Trends and the Evolving Role of Tries&lt;/h2&gt;
&lt;p&gt;As data scales and computational demands grow, Trie data structures continue to evolve and find new relevance. Their core strength—efficient prefix matching—remains a fundamental requirement in many cutting-edge technologies.&lt;/p&gt;
&lt;p&gt;One significant trend is the &lt;strong&gt;integration of Tries with Artificial Intelligence and Machine Learning.&lt;/strong&gt; While traditional Tries operate on exact character matches, modern AI systems often need to handle fuzzy matching, semantic similarity, and contextual relevance. Researchers are exploring ways to augment Tries with machine learning models. For instance, instead of just suggesting prefixes, an AI-enhanced Trie could learn user preferences, query contexts, and even sentiment to provide more intelligent autocomplete suggestions or highly personalized search results. This might involve weighting nodes based on frequency, popularity, or semantic embeddings, allowing Tries to contribute to more sophisticated &lt;a href="/how-to-fine-tune-large-language-models-custom-tasks/"&gt;natural language processing (NLP) tasks&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Another area of development is the &lt;strong&gt;application of Tries in specialized hardware and distributed systems.&lt;/strong&gt; For high-speed packet inspection in network security appliances, or for rapidly routing requests in large-scale microservices architectures, the O(L) lookup speed of Tries is invaluable. Custom hardware accelerators or FPGA implementations of Trie-like structures can perform pattern matching at wire speed, far exceeding the capabilities of general-purpose CPUs. In distributed systems, techniques like Distributed Tries or Trie-based indexing can help manage and query massive datasets across multiple nodes, ensuring low-latency access to prefix-searchable information.&lt;/p&gt;
&lt;p&gt;Furthermore, with the rise of &lt;strong&gt;graph databases and knowledge graphs&lt;/strong&gt;, Tries could play a role in indexing string-based properties or relationships, offering faster navigation through interconnected data based on property prefixes. As the Internet of Things (IoT) generates vast streams of sensor data, Tries might also be employed for efficient pattern detection in time-series data, where sequences of events or measurements could be treated as "strings" for rapid anomaly detection.&lt;/p&gt;
&lt;p&gt;The fundamental principles of Trie data structures, particularly their design for efficient prefix searching, are robust and timeless. While the raw Trie may be adapted, optimized, or combined with other techniques, its underlying paradigm will undoubtedly continue to be a cornerstone of innovation in string processing, search technologies, and beyond. As data continues to grow in volume and complexity, the need for efficient retrieval mechanisms like the Trie will only intensify.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The journey through the intricate world of Trie data structures reveals a powerful, yet elegant, solution for a class of problems that demand efficient string retrieval and prefix matching. From the foundational concept of character-by-character node traversal to advanced optimizations like Radix Trees and Ternary Search Trees, Tries offer unmatched performance for operations central to modern computing. Their O(L) time complexity for search, insertion, and deletion, regardless of the total number of words, makes them indispensable for applications ranging from the familiar autocomplete feature on your smartphone to complex IP routing tables, spell checkers, and bioinformatics research.&lt;/p&gt;
&lt;p&gt;While the space overhead remains a consideration, particularly for vast alphabets or sparse data, the innovations in compressed Tries and specialized variants continually address these limitations, broadening their applicability. Understanding the principles behind &lt;strong&gt;Trie Data Structures: Efficient Prefix Searching Explained&lt;/strong&gt; is not just about mastering an algorithmic concept; it's about grasping a key enabler for responsive, intelligent, and scalable systems in an increasingly data-driven world. As technology advances, the underlying elegance and efficiency of Tries will ensure their continued relevance as a vital tool in the developer's arsenal.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the primary advantage of a Trie data structure?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The main advantage of a Trie is its exceptional efficiency for prefix-based operations, such as searching for words that start with a specific sequence of characters. It offers O(L) time complexity, where L is the length of the key, making it faster than many other data structures for these tasks.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: In what scenarios are Tries generally preferred over Hash Maps?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Tries are preferred over Hash Maps for problems involving prefix searching, autocomplete, spell-checking, and lexicographical ordering. While Hash Maps offer average O(L) lookup, they don't natively support prefix searching, and their performance can degrade with hash collisions.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is a Radix Tree (Patricia Trie) and how does it differ from a standard Trie?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A Radix Tree, or Patricia Trie, is an optimized Trie that saves space by compressing paths. It merges nodes with single children into a single edge labeled with the full string segment. This makes it more memory-efficient, especially for sparse data or long unique suffixes, compared to a standard Trie that uses a node for each character.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Trie"&gt;Trie on Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/trie-data-structure/"&gt;Trie Data Structure - GeeksforGeeks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Radix_tree"&gt;Radix Tree - Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/ternary-search-tree/"&gt;Ternary Search Tree - GeeksforGeeks&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Competitive Programming"/><category term="Technology"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/trie-data-structures-prefix-searching-explained.webp" width="1200"/><media:title type="plain">Trie Data Structures: Efficient Prefix Searching Explained</media:title><media:description type="plain">Explore Trie data structures for lightning-fast prefix searching, a core technique for applications like autocomplete, spell checkers, and efficient routing ...</media:description></entry><entry><title>Implementing Heaps for Efficient Priority Queues: A Deep Dive</title><link href="https://analyticsdrive.tech/implementing-heaps-efficient-priority-queues/" rel="alternate"/><published>2026-03-24T22:10:00+05:30</published><updated>2026-03-24T22:10:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-24:/implementing-heaps-efficient-priority-queues/</id><summary type="html">&lt;p&gt;Deep dive into implementing heaps for efficient priority queues. Grasp their structure, core operations, and widespread applications in algorithms and system...&lt;/p&gt;</summary><content type="html">&lt;p&gt;Mastering efficient data management is crucial in computer science, and a core aspect involves &lt;strong&gt;implementing heaps for efficient priority queues&lt;/strong&gt;, a fundamental solution for managing items based on priority. Whether scheduling tasks, finding shortest paths, or simulating complex events, the ability to efficiently extract the "most important" element is paramount. This is precisely where the concept of a priority queue shines, and among its various implementations, implementing heaps for efficient priority queues stands out as the most practical and performance-driven solution. This article offers a deep dive into the underlying mechanics of heaps, their operational efficiency, and their pervasive utility across diverse computational challenges.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-a-priority-queue"&gt;What is a Priority Queue?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-heaps-the-foundation"&gt;Understanding Heaps: The Foundation&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#min-heap-vs-max-heap"&gt;Min-Heap vs. Max-Heap&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#heap-properties-and-representation"&gt;Heap Properties and Representation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-heaps-for-efficient-priority-queues"&gt;Implementing Heaps for Efficient Priority Queues&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#core-operations-insertion-enqueue"&gt;Core Operations: Insertion (Enqueue)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-operations-extraction-dequeuepop"&gt;Core Operations: Extraction (Dequeue/Pop)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-operations-peekfind-minmax"&gt;Core Operations: Peek/Find Min/Max&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-operations-decreaseincrease-key"&gt;Core Operations: Decrease/Increase Key&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#heap-based-priority-queue-performance-analysis"&gt;Heap-based Priority Queue Performance Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-and-use-cases"&gt;Real-World Applications and Use Cases&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#shortest-path-algorithms-dijkstras-prims"&gt;Shortest Path Algorithms (Dijkstra's, Prim's)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#event-simulation"&gt;Event Simulation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#task-scheduling"&gt;Task Scheduling&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#data-compression-huffman-coding"&gt;Data Compression (Huffman Coding)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#operating-systems-process-management"&gt;Operating Systems (Process Management)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#alternative-implementations-and-why-heaps-excel"&gt;Alternative Implementations and Why Heaps Excel&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#unsorted-arraylist"&gt;Unsorted Array/List&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#sorted-arraylist"&gt;Sorted Array/List&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#binary-search-tree-bst"&gt;Binary Search Tree (BST)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#advanced-heap-variations-and-optimizations"&gt;Advanced Heap Variations and Optimizations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#fibonacci-heaps"&gt;Fibonacci Heaps&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#binomial-heaps"&gt;Binomial Heaps&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#pairing-heaps"&gt;Pairing Heaps&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#best-practices-and-considerations"&gt;Best Practices and Considerations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#language-specific-implementations"&gt;Language-Specific Implementations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#handling-duplicate-priorities"&gt;Handling Duplicate Priorities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#immutability-of-priorities"&gt;Immutability of Priorities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#fixed-size-heaps-top-k-problems"&gt;Fixed-Size Heaps (Top K Problems)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="what-is-a-priority-queue"&gt;What is a Priority Queue?&lt;/h2&gt;
&lt;p&gt;At its core, a priority queue is an abstract data type akin to a regular queue or stack, but with a critical difference: elements are retrieved based on their priority. Unlike a First-In, First-Out (FIFO) queue or a Last-In, First-Out (LIFO) stack, a priority queue ensures that the element with the highest (or lowest) priority is always the first one to be dequeued, regardless of when it was enqueued.&lt;/p&gt;
&lt;p&gt;Think of it as a waiting room where patients aren't called in the order they arrived, but rather based on the severity of their condition. A patient with a critical injury will be seen before someone with a minor ailment, even if the latter arrived earlier. In a computational context, "priority" can be anything from a numerical value (e.g., a cost in a shortest path algorithm, a timestamp in an event simulator) to an inherent property of the data itself.&lt;/p&gt;
&lt;p&gt;The primary operations supported by a priority queue are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Enqueue (Insert):&lt;/strong&gt; Adds a new element with an associated priority into the queue.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Dequeue (Extract-Min/Max):&lt;/strong&gt; Removes and returns the element with the highest (or lowest) priority.
    This is the defining operation.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Peek (Find-Min/Max):&lt;/strong&gt; Returns the element with the highest (or lowest) priority without removing it.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;IsEmpty:&lt;/strong&gt; Checks if the priority queue contains any elements.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Size:&lt;/strong&gt; Returns the number of elements in the priority queue.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;While simple arrays or linked lists can technically implement a priority queue, their performance for key operations like &lt;code&gt;Enqueue&lt;/code&gt; or &lt;code&gt;Dequeue&lt;/code&gt; can degrade significantly. For instance, maintaining a sorted array means &lt;code&gt;Enqueue&lt;/code&gt; could take O(n) time as elements shift, or &lt;code&gt;Dequeue&lt;/code&gt; takes O(n) to find the min/max if unsorted. This is where heaps provide a robust and efficient middle ground, offering logarithmic time complexity for these crucial operations.&lt;/p&gt;
&lt;h2 id="understanding-heaps-the-foundation"&gt;Understanding Heaps: The Foundation&lt;/h2&gt;
&lt;p&gt;Before we delve into the specifics of implementing priority queues, it's essential to grasp the structure and properties of a heap. A heap is a specialized tree-based data structure that satisfies the "heap property" and the "shape property." It's typically implemented as an array, taking advantage of the binary tree structure to efficiently manage parent-child relationships.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Heap Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Shape Property:&lt;/strong&gt; A heap is always a complete binary tree.
    This means all levels of the tree are fully filled, except possibly the last level, which is filled from left to right. This property is crucial because it allows heaps to be efficiently represented using an array, eliminating the need for explicit pointers.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Heap Property:&lt;/strong&gt; This property dictates the ordering of elements within the heap.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Min-Heap:&lt;/strong&gt; For every node &lt;code&gt;i&lt;/code&gt; other than the root, the value of &lt;code&gt;i&lt;/code&gt; is greater than or equal to the value of its parent &lt;code&gt;p&lt;/code&gt;.
    This ensures that the smallest element is always at the root.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Max-Heap:&lt;/strong&gt; For every node &lt;code&gt;i&lt;/code&gt; other than the root, the value of &lt;code&gt;i&lt;/code&gt; is less than or equal to the value of its parent &lt;code&gt;p&lt;/code&gt;.
    This ensures that the largest element is always at the root.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="min-heap-vs-max-heap"&gt;Min-Heap vs. Max-Heap&lt;/h3&gt;
&lt;p&gt;The choice between a min-heap and a max-heap depends entirely on the application's requirement for priority.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Min-Heap:&lt;/strong&gt; If your priority queue needs to always extract the &lt;em&gt;smallest&lt;/em&gt; element (e.g., shortest path, closest event, lowest cost), a min-heap is the appropriate choice.
    The root of a min-heap always contains the minimum value.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Max-Heap:&lt;/strong&gt; If your priority queue needs to always extract the &lt;em&gt;largest&lt;/em&gt; element (e.g., highest priority task, largest value), a max-heap is appropriate.
    The root of a max-heap always contains the maximum value.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For the remainder of this article, unless specified otherwise, we will primarily discuss min-heaps, as they are more commonly used in algorithms like Dijkstra's or Prim's, which often seek minimal costs or distances. The concepts, however, are symmetric for max-heaps.&lt;/p&gt;
&lt;h3 id="heap-properties-and-representation"&gt;Heap Properties and Representation&lt;/h3&gt;
&lt;p&gt;The beauty of heaps lies in their array-based representation. Because a complete binary tree has a predictable structure, we don't need to store explicit left/right child pointers. Instead, the relationships can be calculated using simple arithmetic:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Array Representation of a Heap:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If we store the elements of a heap in an array &lt;code&gt;A&lt;/code&gt;, where the root is at index &lt;code&gt;0&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The parent of node &lt;code&gt;i&lt;/code&gt; is at index &lt;code&gt;(i - 1) // 2&lt;/code&gt; (integer division).&lt;/li&gt;
&lt;li&gt;The left child of node &lt;code&gt;i&lt;/code&gt; is at index &lt;code&gt;2 * i + 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The right child of node &lt;code&gt;i&lt;/code&gt; is at index &lt;code&gt;2 * i + 2&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This compact representation saves memory and allows for very fast access to parent and child nodes. For example, consider a min-heap stored in an array:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;[10, 20, 30, 40, 50, 60, 70]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;Node at index 0 (value 10) is the root.&lt;/li&gt;
&lt;li&gt;Left child of 0 (2&lt;em&gt;0+1 = 1) is 20. Right child of 0 (2&lt;/em&gt;0+2 = 2) is 30.&lt;/li&gt;
&lt;li&gt;Parent of 1 (20) is (1-1)//2 = 0, which is 10.&lt;/li&gt;
&lt;li&gt;All heap properties are maintained: 10 &amp;lt; 20, 10 &amp;lt; 30, 20 &amp;lt; 40, 20 &amp;lt; 50, etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The critical advantage of this representation is its efficiency. Operations involve minimal memory access and simple arithmetic, which translates to superior performance in most scenarios.&lt;/p&gt;
&lt;h2 id="implementing-heaps-for-efficient-priority-queues"&gt;Implementing Heaps for Efficient Priority Queues&lt;/h2&gt;
&lt;p&gt;The core of a heap-based priority queue lies in two primary operations: &lt;code&gt;insert&lt;/code&gt; (or enqueue) and &lt;code&gt;extract-min&lt;/code&gt; (or dequeue). Both operations maintain the heap properties by "bubbling up" or "bubbling down" elements to their correct positions.&lt;/p&gt;
&lt;h3 id="core-operations-insertion-enqueue"&gt;Core Operations: Insertion (Enqueue)&lt;/h3&gt;
&lt;p&gt;When a new element is inserted into a min-heap:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Place at the end:&lt;/strong&gt; The new element is initially added to the next available position in the array (the end of the heap).
    This maintains the &lt;em&gt;shape property&lt;/em&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Bubble Up (Heapify-Up):&lt;/strong&gt; The newly inserted element might violate the &lt;em&gt;heap property&lt;/em&gt; if its value is smaller than its parent's.
    To restore the heap property, the element is repeatedly compared with its parent. If it's smaller, it's swapped with its parent. This process continues upwards towards the root until the element is greater than or equal to its parent, or it reaches the root.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Example of Insertion (Min-Heap):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let's insert &lt;code&gt;5&lt;/code&gt; into the heap &lt;code&gt;[10, 20, 30, 40, 50, 60, 70]&lt;/code&gt;.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Add &lt;code&gt;5&lt;/code&gt; to the end: &lt;code&gt;[10, 20, 30, 40, 50, 60, 70, 5]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;5&lt;/code&gt; (at index 7) is compared with its parent &lt;code&gt;70&lt;/code&gt; (at index &lt;code&gt;(7-1)//2 = 3&lt;/code&gt;). &lt;code&gt;5 &amp;lt; 70&lt;/code&gt;, so swap.
    &lt;code&gt;[10, 20, 30, 5, 50, 60, 70, 40]&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;5&lt;/code&gt; (at index 3) is compared with its parent &lt;code&gt;30&lt;/code&gt; (at index &lt;code&gt;(3-1)//2 = 1&lt;/code&gt;). &lt;code&gt;5 &amp;lt; 30&lt;/code&gt;, so swap.
    &lt;code&gt;[10, 5, 30, 20, 50, 60, 70, 40]&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;5&lt;/code&gt; (at index 1) is compared with its parent &lt;code&gt;10&lt;/code&gt; (at index &lt;code&gt;(1-1)//2 = 0&lt;/code&gt;). &lt;code&gt;5 &amp;lt; 10&lt;/code&gt;, so swap.
    &lt;code&gt;[5, 10, 30, 20, 50, 60, 70, 40]&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;5&lt;/code&gt; is now at the root (index 0), so the process stops. The heap property is restored.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The "bubble up" operation takes at most O(log n) time, as it traverses a path from a leaf to the root, and the height of a complete binary tree with &lt;code&gt;n&lt;/code&gt; nodes is O(log n).&lt;/p&gt;
&lt;h3 id="core-operations-extraction-dequeuepop"&gt;Core Operations: Extraction (Dequeue/Pop)&lt;/h3&gt;
&lt;p&gt;Extracting the minimum (or maximum) element from a heap is a bit more involved:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Store the root:&lt;/strong&gt; The minimum element is always at the root of a min-heap.
    Store this value to return later.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Replace root with last element:&lt;/strong&gt; To maintain the &lt;em&gt;shape property&lt;/em&gt;, the element at the last position of the array is moved to the root.
    The last position is then removed (effectively decreasing the heap's size).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Bubble Down (Heapify-Down):&lt;/strong&gt; The new root element might violate the &lt;em&gt;heap property&lt;/em&gt;.
    To restore it, the element is repeatedly compared with its children. If it's larger than either child (in a min-heap), it's swapped with the &lt;em&gt;smaller&lt;/em&gt; of its two children. This process continues downwards until the element is smaller than or equal to both its children, or it becomes a leaf node.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Example of Extraction (Min-Heap):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let's extract the minimum from the heap &lt;code&gt;[5, 10, 30, 20, 50, 60, 70, 40]&lt;/code&gt;.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Store root &lt;code&gt;5&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Replace root with &lt;code&gt;40&lt;/code&gt; (the last element) and remove &lt;code&gt;40&lt;/code&gt; from its original position. The new heap (conceptually) is &lt;code&gt;[40, 10, 30, 20, 50, 60, 70]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;40&lt;/code&gt; (at index 0) is compared with its children &lt;code&gt;10&lt;/code&gt; (index 1) and &lt;code&gt;30&lt;/code&gt; (index 2).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;10&lt;/code&gt; is smaller than &lt;code&gt;30&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;40 &amp;gt; 10&lt;/code&gt;, so swap &lt;code&gt;40&lt;/code&gt; with &lt;code&gt;10&lt;/code&gt;.
&lt;code&gt;[10, 40, 30, 20, 50, 60, 70]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;40&lt;/code&gt; (at index 1) is compared with its children &lt;code&gt;20&lt;/code&gt; (index &lt;code&gt;2*1+1 = 3&lt;/code&gt;) and &lt;code&gt;50&lt;/code&gt; (index &lt;code&gt;2*1+2 = 4&lt;/code&gt;).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;20&lt;/code&gt; is smaller than &lt;code&gt;50&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;40 &amp;gt; 20&lt;/code&gt;, so swap &lt;code&gt;40&lt;/code&gt; with &lt;code&gt;20&lt;/code&gt;.
&lt;code&gt;[10, 20, 30, 40, 50, 60, 70]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;40&lt;/code&gt; (at index 3) is compared with its children (which would be at indices 7 and 8, but those are out of bounds for the current heap size). &lt;code&gt;40&lt;/code&gt; is now a leaf node. The process stops. The heap property is restored.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;Return the stored value &lt;code&gt;5&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The "bubble down" operation also takes at most O(log n) time, as it traverses a path from the root to a leaf, which is the height of the tree.&lt;/p&gt;
&lt;h3 id="core-operations-peekfind-minmax"&gt;Core Operations: Peek/Find Min/Max&lt;/h3&gt;
&lt;p&gt;This operation is straightforward: simply return the value at the root of the heap (index 0 in the array representation). It does not modify the heap.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(1)&lt;/p&gt;
&lt;h3 id="core-operations-decreaseincrease-key"&gt;Core Operations: Decrease/Increase Key&lt;/h3&gt;
&lt;p&gt;These operations are crucial in algorithms like Dijkstra's, where the priority of an element already in the queue might change.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Decrease Key (Min-Heap):&lt;/strong&gt; Find the element, update its priority to a smaller value, then perform a &lt;code&gt;bubble up&lt;/code&gt; operation from that element's new position.
    This is because a decreased key might now be smaller than its parent, violating the heap property upwards.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Increase Key (Min-Heap):&lt;/strong&gt; Find the element, update its priority to a larger value, then perform a &lt;code&gt;bubble down&lt;/code&gt; operation from that element's new position.
    This is because an increased key might now be larger than its children, violating the heap property downwards.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The challenge with these operations is efficiently &lt;em&gt;finding&lt;/em&gt; the element whose priority needs to be changed. If the heap only supports value-based operations, finding an arbitrary element typically requires O(n) traversal. To achieve O(log n) for &lt;code&gt;decrease-key&lt;/code&gt; (which is often required), the priority queue implementation usually needs to store additional metadata, such as a mapping from the actual item to its current index in the heap array. This is common in many advanced graph algorithms.&lt;/p&gt;
&lt;h2 id="heap-based-priority-queue-performance-analysis"&gt;Heap-based Priority Queue Performance Analysis&lt;/h2&gt;
&lt;p&gt;The efficiency of implementing heaps for efficient priority queues is a major reason for their widespread adoption. Let's break down the time and space complexity of their fundamental operations.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Enqueue (Insertion):&lt;/strong&gt; O(log n)&lt;ul&gt;
&lt;li&gt;Adding an element to the end of the array is O(1).&lt;/li&gt;
&lt;li&gt;The subsequent &lt;code&gt;bubble up&lt;/code&gt; operation traverses at most the height of the tree, which is log n. Hence, the total time is O(log n).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dequeue (Extract-Min/Max):&lt;/strong&gt; O(log n)&lt;ul&gt;
&lt;li&gt;Accessing the root element is O(1).&lt;/li&gt;
&lt;li&gt;Replacing the root with the last element and adjusting the array is O(1).&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;bubble down&lt;/code&gt; operation traverses at most the height of the tree, which is log n. Hence, the total time is O(log n).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Peek (Find-Min/Max):&lt;/strong&gt; O(1)&lt;ul&gt;
&lt;li&gt;Directly accessing the root element in the array takes constant time.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Decrease/Increase Key:&lt;/strong&gt; O(log n)&lt;ul&gt;
&lt;li&gt;Assuming the position of the element to be updated is known (e.g., through an auxiliary lookup table), updating its value is O(1).&lt;/li&gt;
&lt;li&gt;The subsequent &lt;code&gt;bubble up&lt;/code&gt; or &lt;code&gt;bubble down&lt;/code&gt; operation takes O(log n). Without knowing the element's position, finding it would be O(n).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Compared to alternative priority queue implementations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Unsorted List/Array:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Insertion is O(1).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Extract-Min/Max&lt;/code&gt; is O(n) (requires scanning the whole list).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Why Heaps Excel:&lt;/strong&gt; While insertion is faster, the O(n) for extraction quickly becomes a bottleneck for large datasets or frequent extractions. Heaps reduce this to O(log n), making them far more scalable.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Sorted List/Array:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Insertion is O(n).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Extract-Min/Max&lt;/code&gt; is O(1).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Why Heaps Excel:&lt;/strong&gt; Good for scenarios with many extractions and few insertions. However, if insertions are frequent, the O(n) cost quickly outweighs the O(1) extraction benefit. Heaps balance both operations at O(log n).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;a href="https://analyticsdrive.tech/binary-search-tree/"&gt;Binary Search Tree&lt;/a&gt; (BST):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Insertion is O(h), where &lt;code&gt;h&lt;/code&gt; is the height of the tree.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Extract-Min/Max&lt;/code&gt; is O(h).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Why Heaps Excel:&lt;/strong&gt; While a BST can also provide O(log n) average-case performance, its worst-case can be O(n). To guarantee O(log n), one must use a self-balancing BST (like an AVL tree or Red-Black tree), which are significantly more complex to &lt;a href="/how-to-implement-binary-search-tree-python/"&gt;implement a Binary Search Tree&lt;/a&gt; and maintain than a simple heap. Heaps provide guaranteed O(log n) performance for priority queue operations with simpler code and less overhead. Furthermore, for priority queue specific tasks (extract min/max), heaps are generally faster in practice due to better cache locality with array-based storage.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Heaps provide a consistent O(log n) performance for both insertion and extraction, striking an excellent balance that makes them ideal for a vast range of applications where frequent additions and removals are expected.&lt;/p&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(n)&lt;ul&gt;
&lt;li&gt;A heap implemented using an array stores &lt;code&gt;n&lt;/code&gt; elements, requiring space proportional to the number of elements.&lt;/li&gt;
&lt;li&gt;This is generally efficient as it uses contiguous memory and doesn't incur the overhead of storing explicit pointers for tree nodes, as would be the case for a linked tree structure.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The efficient memory usage and predictable performance make heaps a cornerstone data structure for high-performance computing and algorithm design.&lt;/p&gt;
&lt;h2 id="real-world-applications-and-use-cases"&gt;Real-World Applications and Use Cases&lt;/h2&gt;
&lt;p&gt;The practical utility of implementing heaps for efficient priority queues extends across numerous domains in computer science and engineering. Their ability to consistently provide the highest (or lowest) priority element makes them indispensable for optimization, scheduling, and graph traversal.&lt;/p&gt;
&lt;h3 id="shortest-path-algorithms-dijkstras-prims"&gt;Shortest Path Algorithms (Dijkstra's, Prim's)&lt;/h3&gt;
&lt;p&gt;Perhaps one of the most famous applications, &lt;a href="/dijkstras-algorithm-shortest-path-explained/"&gt;Dijkstra's algorithm&lt;/a&gt; for finding the shortest path from a single source to all other vertices in a weighted graph relies heavily on a min-priority queue. Each vertex is associated with a temporary distance (priority). The algorithm repeatedly extracts the unvisited vertex with the smallest tentative distance from the priority queue, relaxes its neighbors' distances, and updates their priorities in the queue. Without an efficient priority queue (like a heap), Dijkstra's complexity would be much higher.&lt;/p&gt;
&lt;p&gt;Similarly, Prim's algorithm for finding a minimum spanning tree (MST) also uses a min-priority queue. It maintains a set of vertices already in the MST and a priority queue of edges connecting these vertices to unvisited ones, prioritizing edges with minimum weight.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Graph Representation:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;Vertices: A, B, C, D, E
Edges: (A,B,4), (A,C,2), (B,E,3), (C,D,2), (D,E,3)
Source vertex: A
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;In Dijkstra's, the priority queue would store &lt;code&gt;(distance, vertex)&lt;/code&gt;, and we'd always extract the &lt;code&gt;(min_distance, vertex)&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="event-simulation"&gt;Event Simulation&lt;/h3&gt;
&lt;p&gt;Discrete event simulation (DES) models the operation of a system as a discrete sequence of events in time. A priority queue is crucial for managing these events. Each event is placed into the priority queue with its scheduled occurrence time as its priority. The simulation engine then repeatedly extracts the event with the earliest time, executes it, and possibly generates new events that are then added back to the queue. This ensures that events are processed in chronological order. Examples include simulating queues in a bank, traffic flow, or network protocols.&lt;/p&gt;
&lt;h3 id="task-scheduling"&gt;Task Scheduling&lt;/h3&gt;
&lt;p&gt;Operating systems, especially real-time operating systems (RTOS), and job schedulers often use priority queues to manage processes or tasks. Each task is assigned a priority, and the scheduler extracts the highest-priority task ready for execution. This allows critical tasks to preempt less important ones, ensuring responsiveness and meeting deadlines. Similarly, cloud computing platforms might use priority queues to schedule virtual machine deployments or resource allocations based on user-defined priorities or service-level agreements.&lt;/p&gt;
&lt;h3 id="data-compression-huffman-coding"&gt;Data Compression (Huffman Coding)&lt;/h3&gt;
&lt;p&gt;Huffman coding is a widely used algorithm for lossless data compression. It constructs a binary tree where frequently occurring characters have shorter binary codes. The construction of this Huffman tree involves a min-priority queue. Initially, each character is treated as a leaf node with its frequency as its priority. The algorithm repeatedly extracts the two nodes with the lowest frequencies from the priority queue, merges them into a new internal node whose frequency is the sum of its children's frequencies, and inserts this new node back into the priority queue. This process continues until only one node (the root of the Huffman tree) remains.&lt;/p&gt;
&lt;h3 id="operating-systems-process-management"&gt;Operating Systems (Process Management)&lt;/h3&gt;
&lt;p&gt;Beyond task scheduling, operating systems also employ priority queues for managing various internal resources. For instance, managing I/O requests where certain processes or device operations have higher precedence, or in memory management where certain memory blocks might be prioritized for eviction or allocation. The core principle remains selecting the "best" candidate according to defined criteria.&lt;/p&gt;
&lt;p&gt;These examples underscore the versatility and foundational importance of implementing heaps for efficient priority queues across diverse computational challenges, from fundamental algorithms to complex system architectures.&lt;/p&gt;
&lt;h2 id="alternative-implementations-and-why-heaps-excel"&gt;Alternative Implementations and Why Heaps Excel&lt;/h2&gt;
&lt;p&gt;While heaps offer an excellent balance of performance, it's insightful to consider alternative ways to implement a priority queue and understand why heaps are often preferred.&lt;/p&gt;
&lt;h3 id="unsorted-arraylist"&gt;Unsorted Array/List&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion:&lt;/strong&gt; O(1).
    Simply append the new element to the end of the array or list.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Extract-Min/Max:&lt;/strong&gt; O(n).
    To find the minimum or maximum element, you must traverse the entire array/list. Once found, removing it can also take O(n) if elements need to be shifted.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Why Heaps Excel:&lt;/strong&gt; While insertion is faster, the O(n) for extraction quickly becomes a bottleneck for large datasets or frequent extractions. Heaps reduce this to O(log n), making them far more scalable.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="sorted-arraylist"&gt;Sorted Array/List&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion:&lt;/strong&gt; O(n).
    To maintain sorted order, a new element must be inserted at its correct position, potentially requiring shifting all subsequent elements.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Extract-Min/Max:&lt;/strong&gt; O(1).
    The minimum/maximum element is always at one end of the sorted array/list, and removal is trivial.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Why Heaps Excel:&lt;/strong&gt; Good for scenarios with many extractions and few insertions. However, if insertions are frequent, the O(n) cost quickly outweighs the O(1) extraction benefit. Heaps balance both operations at O(log n).&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="binary-search-tree-bst"&gt;Binary Search Tree (BST)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion:&lt;/strong&gt; O(h), where &lt;code&gt;h&lt;/code&gt; is the height of the tree.
    In the average case, &lt;code&gt;h = O(log n)&lt;/code&gt;, but in the worst case (e.g., inserting elements in sorted order), &lt;code&gt;h = O(n)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Extract-Min/Max:&lt;/strong&gt; O(h).
    Finding the minimum (leftmost node) or maximum (rightmost node) and then deleting it takes time proportional to the height.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Why Heaps Excel:&lt;/strong&gt; While a BST can also provide O(log n) average-case performance, its worst-case can be O(n). To guarantee O(log n), one must use a self-balancing BST (like an AVL tree or Red-Black tree), which are significantly more complex to &lt;a href="/how-to-implement-binary-search-tree-python/"&gt;implement a Binary Search Tree&lt;/a&gt; and maintain than a simple heap. Heaps provide guaranteed O(log n) performance for priority queue operations with simpler code and less overhead. Furthermore, for priority queue specific tasks (extract min/max), heaps are generally faster in practice due to better cache locality with array-based storage.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The key takeaway is that heaps offer a near-optimal balance for the core priority queue operations—insertion and extraction—both performing in logarithmic time. This makes them a superior choice for dynamic scenarios where elements are frequently added and removed, requiring consistent performance. The simplicity of their array-based implementation further enhances their appeal over more complex balanced tree structures for this specific problem.&lt;/p&gt;
&lt;h2 id="advanced-heap-variations-and-optimizations"&gt;Advanced Heap Variations and Optimizations&lt;/h2&gt;
&lt;p&gt;While the binary heap is the most common and practical choice for implementing priority queues, researchers have developed several advanced heap structures to optimize specific operations, particularly for very large datasets or specialized algorithms. These variations often offer better asymptotic performance for certain operations, though usually at the cost of increased complexity.&lt;/p&gt;
&lt;h3 id="fibonacci-heaps"&gt;Fibonacci Heaps&lt;/h3&gt;
&lt;p&gt;Fibonacci heaps are a more sophisticated heap structure primarily used in theoretical computer science and for implementing graph algorithms on very dense graphs (where the number of edges is close to the square of the number of vertices). They offer improved amortized time complexity for some operations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Insertion:&lt;/strong&gt; O(1) amortized&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Extract-Min:&lt;/strong&gt; O(log n) amortized&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Decrease-Key:&lt;/strong&gt; O(1) amortized&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Merge:&lt;/strong&gt; O(1) amortized&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The O(1) amortized &lt;code&gt;decrease-key&lt;/code&gt; operation is particularly valuable for algorithms like Dijkstra's and Prim's on dense graphs, where many &lt;code&gt;decrease-key&lt;/code&gt; operations occur. While theoretically superior, their high constant factors and implementation complexity mean they are rarely used in general-purpose programming contexts outside of specific research or high-performance library implementations.&lt;/p&gt;
&lt;h3 id="binomial-heaps"&gt;Binomial Heaps&lt;/h3&gt;
&lt;p&gt;Binomial heaps are another collection of specialized heaps that support efficient merging of two heaps, a feature not natively efficient in binary heaps (which would require inserting all elements from one into another).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Insertion:&lt;/strong&gt; O(1) amortized&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Extract-Min:&lt;/strong&gt; O(log n)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Decrease-Key:&lt;/strong&gt; O(log n)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Merge:&lt;/strong&gt; O(log n)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;They are often implemented as a forest of binomial trees, where each tree satisfies the min-heap property. Binomial heaps find niches where frequent merging of priority queues is a dominant operation.&lt;/p&gt;
&lt;h3 id="pairing-heaps"&gt;Pairing Heaps&lt;/h3&gt;
&lt;p&gt;Pairing heaps are a relatively simple-to-implement heap structure that often performs very well in practice, even though their worst-case theoretical bounds are not as strong as Fibonacci heaps. They are "pairing" heaps because they rely on pairwise comparisons and merging of sub-heaps.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Insertion:&lt;/strong&gt; O(1) amortized&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Extract-Min:&lt;/strong&gt; O(log n) amortized (some analyses show O(log n) worst-case)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Decrease-Key:&lt;/strong&gt; O(log n) amortized (some analyses show O(1) amortized)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Despite some open questions regarding their precise theoretical bounds, pairing heaps are considered a good practical choice when &lt;code&gt;decrease-key&lt;/code&gt; operations are frequent and a simpler implementation than Fibonacci heaps is desired. They strike a balance between theoretical elegance and practical efficiency.&lt;/p&gt;
&lt;p&gt;For most general-purpose applications, the binary heap remains the go-to choice due to its simplicity, robust performance, and excellent cache locality. However, awareness of these advanced variants highlights the depth of research in optimizing priority queue performance for specialized computational challenges.&lt;/p&gt;
&lt;h2 id="best-practices-and-considerations"&gt;Best Practices and Considerations&lt;/h2&gt;
&lt;p&gt;When implementing or utilizing heap-based priority queues, a few best practices and considerations can optimize their use and ensure robust performance.&lt;/p&gt;
&lt;h3 id="language-specific-implementations"&gt;Language-Specific Implementations&lt;/h3&gt;
&lt;p&gt;Many programming languages offer built-in or standard library modules for heaps or priority queues, often implemented as binary heaps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Python:&lt;/strong&gt; The &lt;code&gt;heapq&lt;/code&gt; module provides an implementation of the heap queue algorithm.
    It treats a regular Python list as a heap, meaning it's not a separate data type but a set of functions that operate on lists to maintain heap properties. This makes it very flexible.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Java:&lt;/strong&gt; The &lt;code&gt;java.util.PriorityQueue&lt;/code&gt; class implements a min-priority queue by default (a max-priority queue can be achieved with a custom &lt;code&gt;Comparator&lt;/code&gt;).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;C++:&lt;/strong&gt; The &lt;code&gt;std::priority_queue&lt;/code&gt; in the Standard Template Library (STL) is a container adapter that provides a max-priority queue by default.
    It can be customized to be a min-priority queue using a &lt;code&gt;std::greater&lt;/code&gt; comparator.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Leveraging these well-tested and optimized built-in solutions is almost always preferable to writing a custom heap implementation from scratch, unless specific non-standard features or extreme performance tuning are required.&lt;/p&gt;
&lt;h3 id="handling-duplicate-priorities"&gt;Handling Duplicate Priorities&lt;/h3&gt;
&lt;p&gt;Heaps inherently handle duplicate priorities without issue. If multiple elements have the same highest priority, any one of them can be extracted. The exact one depends on the stable ordering of the heapify operations and the specific implementation. If a strict tie-breaking rule is needed (e.g., FIFO among same-priority items), additional logic (like storing an insertion timestamp as a secondary priority) might be required.&lt;/p&gt;
&lt;h3 id="immutability-of-priorities"&gt;Immutability of Priorities&lt;/h3&gt;
&lt;p&gt;For &lt;code&gt;decrease-key&lt;/code&gt; or &lt;code&gt;increase-key&lt;/code&gt; operations to be efficient (O(log n)), you typically need a way to quickly find an element's current position in the heap. If your elements are complex objects, you might need an auxiliary data structure (like a &lt;a href="/what-is-a-hash-map-hashing-concepts/"&gt;hash map&lt;/a&gt;) to map the object to its current index in the heap array. Modifying an element's priority without updating its position can violate the heap property and lead to incorrect behavior.&lt;/p&gt;
&lt;h3 id="fixed-size-heaps-top-k-problems"&gt;Fixed-Size Heaps (Top K Problems)&lt;/h3&gt;
&lt;p&gt;For problems requiring the "top K" smallest or largest elements, a fixed-size heap can be used. For the top K largest, maintain a min-heap of size K. Iterate through the input: if an element is larger than the heap's root, remove the root and insert the new element. If it's smaller, ignore it. This keeps the heap size to K, and its root will be the K-th largest element (and all elements in the heap will be the top K largest). This pattern is very common in competitive programming and data processing.&lt;/p&gt;
&lt;p&gt;By understanding these practical considerations, developers can effectively utilize heap-based priority queues to solve a wide array of problems efficiently and robustly.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The journey into &lt;strong&gt;implementing heaps for efficient priority queues&lt;/strong&gt; reveals a powerful and elegant solution to a ubiquitous problem in computer science. From the fundamental principles of the heap property and array-based representation to the detailed mechanics of &lt;code&gt;insert&lt;/code&gt; and &lt;code&gt;extract-min&lt;/code&gt; operations, we've seen how heaps consistently deliver logarithmic time complexity, a critical advantage over simpler data structures.&lt;/p&gt;
&lt;p&gt;Their consistent O(log n) performance for core operations, coupled with efficient space utilization, makes them the de facto standard for priority queue implementations. This efficiency is not merely theoretical; it underpins the practical viability of crucial algorithms like Dijkstra's for shortest paths, Prim's for minimum spanning trees, and is essential for effective task scheduling, event simulation, and data compression techniques like Huffman coding.&lt;/p&gt;
&lt;p&gt;While advanced heap variants offer specialized optimizations for particular scenarios, the binary heap remains the workhorse, balancing simplicity with high performance. By understanding and effectively leveraging heaps, developers gain a potent tool for optimizing algorithms, managing dynamic data, and building highly responsive and efficient systems. The mastery of this data structure is undoubtedly a valuable asset for any tech-savvy individual navigating the complexities of modern computing.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is a heap?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A heap is a specialized tree-based data structure that satisfies two main properties: the heap property (defining the parent-child ordering) and the shape property (being a complete binary tree). It's typically implemented using an array, which allows for efficient calculation of parent and child indices.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Why are heaps efficient for priority queues?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Heaps are efficient for priority queues because they offer a consistent O(log n) time complexity for both inserting new elements and extracting the highest (or lowest) priority element. This logarithmic performance significantly outperforms simpler data structures like unsorted or sorted arrays for dynamic scenarios with frequent additions and removals.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is a priority queue used for?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Priority queues have widespread applications, including implementing graph algorithms like Dijkstra's for shortest paths and Prim's for minimum spanning trees, managing tasks and processes in operating systems, scheduling events in simulations, and in data compression techniques such as Huffman coding.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Priority_queue"&gt;Priority Queue - Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Heap_(data_structure)"&gt;Heap (data structure) - Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/introduction-to-heap-data-structure-and-algorithm-tutorials/"&gt;Introduction to Heaps - GeeksforGeeks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.python.org/3/library/heapq.html"&gt;Python heapq module documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/PriorityQueue.html"&gt;Java PriorityQueue documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Competitive Programming"/><category term="Graph Theory"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/implementing-heaps-efficient-priority-queues.webp" width="1200"/><media:title type="plain">Implementing Heaps for Efficient Priority Queues: A Deep Dive</media:title><media:description type="plain">Deep dive into implementing heaps for efficient priority queues. Grasp their structure, core operations, and widespread applications in algorithms and system...</media:description></entry><entry><title>Dijkstra's Algorithm: Shortest Path Finding Explained In Depth</title><link href="https://analyticsdrive.tech/dijkstras-algorithm-shortest-path-explained/" rel="alternate"/><published>2026-03-23T13:46:00+05:30</published><updated>2026-03-23T13:46:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-23:/dijkstras-algorithm-shortest-path-explained/</id><summary type="html">&lt;p&gt;Demystify Dijkstra's Algorithm, the core of shortest path finding. Explore its mechanics, applications, and complexity, powering navigation and network routing.&lt;/p&gt;</summary><content type="html">&lt;p&gt;In the intricate world of computer science and network theory, efficiently navigating complex structures is paramount. One fundamental problem that underpins countless modern technologies is finding the shortest path between two points in a graph. This seemingly simple challenge has profound implications, from optimizing logistics to powering the internet itself. For those seeking a truly comprehensive understanding, we will now explore &lt;strong&gt;Dijkstra's Algorithm: Shortest Path Finding Explained In Depth&lt;/strong&gt;, delving into its elegant mechanics and robust applications. This powerful algorithm provides a systematic way to uncover the optimal route, making it an indispensable tool for developers, data scientists, and anyone keen to unravel the complexities of graph theory.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-dijkstras-algorithm"&gt;What is Dijkstra's Algorithm?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#deep-dive-into-dijkstras-algorithm-shortest-path-finding-explained"&gt;Deep Dive into Dijkstra's Algorithm: Shortest Path Finding Explained&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-core-idea-greedy-approach-and-relaxation"&gt;The Core Idea: Greedy Approach and Relaxation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#illustrative-example-step-by-step-traversal"&gt;Illustrative Example: Step-by-Step Traversal&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#key-components-and-features"&gt;Key Components and Features&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#graph-representation"&gt;Graph Representation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#priority-queue"&gt;Priority Queue&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#non-negative-edge-weights-constraint"&gt;Non-Negative Edge Weights Constraint&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-dijkstras-algorithm"&gt;Real-World Applications of Dijkstra's Algorithm&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-gps-and-navigation-systems"&gt;1. GPS and Navigation Systems&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-network-routing-protocols"&gt;2. Network Routing Protocols&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-telecommunication-networks"&gt;3. Telecommunication Networks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-logistics-and-supply-chain-management"&gt;4. Logistics and Supply Chain Management&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-urban-planning-and-transportation"&gt;5. Urban Planning and Transportation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6-social-network-analysis"&gt;6. Social Network Analysis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#7-game-development-ai-pathfinding"&gt;7. Game Development (AI Pathfinding)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#8-image-processing"&gt;8. Image Processing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#pros-and-cons-of-dijkstras-algorithm"&gt;Pros and Cons of Dijkstra's Algorithm&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#advantages-pros"&gt;Advantages (Pros)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#disadvantages-cons"&gt;Disadvantages (Cons)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#related-algorithms-and-comparison"&gt;Related Algorithms and Comparison&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#bellman-ford-algorithm"&gt;Bellman-Ford Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#a-search-algorithm"&gt;A* Search Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#floyd-warshall-algorithm"&gt;Floyd-Warshall Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#prims-algorithm-and-kruskals-algorithm"&gt;Prim's Algorithm and Kruskal's Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#future-outlook-and-advanced-considerations"&gt;Future Outlook and Advanced Considerations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#large-scale-graphs-and-performance-optimization"&gt;Large-Scale Graphs and Performance Optimization&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#dynamic-graphs"&gt;Dynamic Graphs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#probabilistic-and-stochastic-shortest-paths"&gt;Probabilistic and Stochastic Shortest Paths&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#quantum-computing-and-graph-algorithms"&gt;Quantum Computing and Graph Algorithms&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="what-is-dijkstras-algorithm"&gt;What is Dijkstra's Algorithm?&lt;/h2&gt;
&lt;p&gt;Dijkstra's Algorithm, conceived by Dutch computer scientist Edsger W. Dijkstra in 1956 and published in 1959, is a renowned &lt;a href="/graph-traversal-bfs-dfs-interviews/"&gt;graph search algorithm&lt;/a&gt; that solves the single-source shortest path problem for a graph with non-negative edge weights. This means it finds the shortest paths from a single starting node (the "source") to all other nodes in the graph. Imagine planning a road trip where you want the quickest route from your home to every major city; Dijkstra's algorithm is precisely what would enable such a calculation, assuming no one-way streets drastically alter the travel time in a negative way (i.e., no shortcuts that somehow put you back in time).&lt;/p&gt;
&lt;p&gt;The core principle behind Dijkstra's algorithm is its "greedy" approach. At each step, it makes the locally optimal choice in the hope that this choice will lead to a globally optimal solution. It iteratively explores unvisited nodes, expanding the shortest path found so far from the source. The algorithm meticulously maintains a set of visited nodes and an estimation of the shortest distance from the source to every other node, refining these estimations until the true shortest path is discovered for all reachable nodes. This methodical expansion guarantees correctness for its specific problem domain.&lt;/p&gt;
&lt;p&gt;Unlike some other pathfinding algorithms, Dijkstra's is particularly well-suited for scenarios where edge costs consistently represent actual 'distances' or 'costs' that accumulate positively. Its robustness and relative simplicity make it a cornerstone of graph theory and an essential topic for anyone delving into algorithms or network optimization. The insights it provides are not just theoretical; they directly translate into tangible improvements in performance and efficiency across a wide array of computational tasks.&lt;/p&gt;
&lt;h2 id="deep-dive-into-dijkstras-algorithm-shortest-path-finding-explained"&gt;Deep Dive into Dijkstra's Algorithm: Shortest Path Finding Explained&lt;/h2&gt;
&lt;p&gt;To truly grasp the power and elegance of Dijkstra's Algorithm: Shortest Path Finding Explained, it’s essential to break down its operational mechanics. The algorithm works by building a set of nodes for which the shortest path from the source has been finalized. It then iteratively selects the node with the smallest distance value from the unvisited set and relaxes its edges, updating the distances of its neighbors if a shorter path is found. This process continues until all reachable nodes have been visited.&lt;/p&gt;
&lt;h3 id="the-core-idea-greedy-approach-and-relaxation"&gt;The Core Idea: Greedy Approach and Relaxation&lt;/h3&gt;
&lt;p&gt;At its heart, Dijkstra's algorithm employs a greedy strategy. It assumes that if we've found the shortest path to a node &lt;code&gt;u&lt;/code&gt;, and we want to find the shortest path to its neighbor &lt;code&gt;v&lt;/code&gt;, the shortest path to &lt;code&gt;v&lt;/code&gt; will involve the shortest path to &lt;code&gt;u&lt;/code&gt; plus the edge weight between &lt;code&gt;u&lt;/code&gt; and &lt;code&gt;v&lt;/code&gt;. This isn't just an assumption; it's provably correct for graphs with non-negative edge weights due to the principle of optimal substructure.&lt;/p&gt;
&lt;p&gt;The "relaxation" step is critical. For an edge &lt;code&gt;(u, v)&lt;/code&gt; with weight &lt;code&gt;w(u, v)&lt;/code&gt;, if the current shortest distance to &lt;code&gt;v&lt;/code&gt; (&lt;code&gt;dist[v]&lt;/code&gt;) is greater than the shortest distance to &lt;code&gt;u&lt;/code&gt; (&lt;code&gt;dist[u]&lt;/code&gt;) plus the weight of the edge (&lt;code&gt;w(u, v)&lt;/code&gt;), then we've found a shorter path to &lt;code&gt;v&lt;/code&gt; through &lt;code&gt;u&lt;/code&gt;. In this case, we update &lt;code&gt;dist[v]&lt;/code&gt; to &lt;code&gt;dist[u] + w(u, v)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Initialization Steps:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Distance Array:&lt;/strong&gt; Create a &lt;code&gt;dist&lt;/code&gt; array (or map) for all nodes, initializing &lt;code&gt;dist[source]&lt;/code&gt; to 0 and all other &lt;code&gt;dist[v]&lt;/code&gt; to infinity. This array will store the shortest distance found so far from the source to each node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Parent/Predecessor Array (Optional):&lt;/strong&gt; Create a &lt;code&gt;prev&lt;/code&gt; array to reconstruct the path later. Initialize all &lt;code&gt;prev[v]&lt;/code&gt; to &lt;code&gt;null&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Priority Queue:&lt;/strong&gt; Use a min-priority queue (min-heap) to store pairs of &lt;code&gt;(distance, node)&lt;/code&gt;. Initially, insert &lt;code&gt;(0, source)&lt;/code&gt; into the priority queue. The priority queue efficiently allows us to extract the node with the smallest distance discovered so far.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Main Algorithm Loop:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The algorithm proceeds in a loop while the priority queue is not empty:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Extract Minimum:&lt;/strong&gt; Extract the node &lt;code&gt;u&lt;/code&gt; with the smallest &lt;code&gt;dist[u]&lt;/code&gt; from the priority queue. This &lt;code&gt;u&lt;/code&gt; is guaranteed to have its shortest path from the source finalized.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visited Check:&lt;/strong&gt; If &lt;code&gt;u&lt;/code&gt; has already been visited (i.e., its shortest path already finalized), continue to the next iteration. This check is crucial if you're using a priority queue that allows multiple entries for the same node (which is common for efficiency).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark Visited:&lt;/strong&gt; Mark &lt;code&gt;u&lt;/code&gt; as visited.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Relax Neighbors:&lt;/strong&gt; For each neighbor &lt;code&gt;v&lt;/code&gt; of &lt;code&gt;u&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;Calculate &lt;code&gt;new_distance = dist[u] + weight(u, v)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;new_distance &amp;lt; dist[v]&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;Update &lt;code&gt;dist[v] = new_distance&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Update &lt;code&gt;prev[v] = u&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Insert &lt;code&gt;(new_distance, v)&lt;/code&gt; into the priority queue.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This loop ensures that the algorithm always processes the closest unvisited node, thereby guaranteeing that when a node &lt;code&gt;u&lt;/code&gt; is extracted from the priority queue, &lt;code&gt;dist[u]&lt;/code&gt; holds its true shortest distance from the source.&lt;/p&gt;
&lt;h3 id="illustrative-example-step-by-step-traversal"&gt;Illustrative Example: Step-by-Step Traversal&lt;/h3&gt;
&lt;p&gt;Let's consider a simple directed graph to visualize Dijkstra's Algorithm in action.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Graph Representation:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;Vertices: A, B, C, D, E
Edges:
(A, B, 10)
(A, C, 3)
(B, D, 2)
(C, B, 4)
(C, D, 8)
(C, E, 2)
(D, E, 5)
Source vertex: A
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dist = {A: 0, B: ∞, C: ∞, D: ∞, E: ∞}&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;prev = {A: null, B: null, C: null, D: null, E: null}&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;priority_queue = [(0, A)]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;visited = {}&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Iteration 1:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Extract Min:&lt;/strong&gt; &lt;code&gt;(0, A)&lt;/code&gt; is extracted. &lt;code&gt;dist[A]&lt;/code&gt; is finalized to 0.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark Visited:&lt;/strong&gt; &lt;code&gt;visited = {A}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Relax Neighbors of A:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Neighbor B: &lt;code&gt;new_distance = dist[A] + weight(A, B) = 0 + 10 = 10&lt;/code&gt;. Since &lt;code&gt;10 &amp;lt; dist[B]&lt;/code&gt; (∞), update &lt;code&gt;dist[B] = 10&lt;/code&gt;, &lt;code&gt;prev[B] = A&lt;/code&gt;. Add &lt;code&gt;(10, B)&lt;/code&gt; to PQ.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Neighbor C: &lt;code&gt;new_distance = dist[A] + weight(A, C) = 0 + 3 = 3&lt;/code&gt;. Since &lt;code&gt;3 &amp;lt; dist[C]&lt;/code&gt; (∞), update &lt;code&gt;dist[C] = 3&lt;/code&gt;, &lt;code&gt;prev[C] = A&lt;/code&gt;. Add &lt;code&gt;(3, C)&lt;/code&gt; to PQ.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;dist = {A: 0, B: 10, C: 3, D: ∞, E: ∞}&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;priority_queue = [(3, C), (10, B)]&lt;/code&gt; (order depends on PQ implementation, here smallest distance first)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Iteration 2:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Extract Min:&lt;/strong&gt; &lt;code&gt;(3, C)&lt;/code&gt; is extracted. &lt;code&gt;dist[C]&lt;/code&gt; is finalized to 3.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark Visited:&lt;/strong&gt; &lt;code&gt;visited = {A, C}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Relax Neighbors of C:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Neighbor B: &lt;code&gt;new_distance = dist[C] + weight(C, B) = 3 + 4 = 7&lt;/code&gt;. Since &lt;code&gt;7 &amp;lt; dist[B]&lt;/code&gt; (10), update &lt;code&gt;dist[B] = 7&lt;/code&gt;, &lt;code&gt;prev[B] = C&lt;/code&gt;. Add &lt;code&gt;(7, B)&lt;/code&gt; to PQ. (Note: B is now in PQ twice, once with 10, once with 7. The PQ will prioritize 7).&lt;/li&gt;
&lt;li&gt;Neighbor D: &lt;code&gt;new_distance = dist[C] + weight(C, D) = 3 + 8 = 11&lt;/code&gt;. Since &lt;code&gt;11 &amp;lt; dist[D]&lt;/code&gt; (∞), update &lt;code&gt;dist[D] = 11&lt;/code&gt;, &lt;code&gt;prev[D] = C&lt;/code&gt;. Add &lt;code&gt;(11, D)&lt;/code&gt; to PQ.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Neighbor E: &lt;code&gt;new_distance = dist[C] + weight(C, E) = 3 + 2 = 5&lt;/code&gt;. Since &lt;code&gt;5 &amp;lt; dist[E]&lt;/code&gt; (∞), update &lt;code&gt;dist[E] = 5&lt;/code&gt;, &lt;code&gt;prev[E] = C&lt;/code&gt;. Add &lt;code&gt;(5, E)&lt;/code&gt; to PQ.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;dist = {A: 0, B: 7, C: 3, D: 11, E: 5}&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;priority_queue = [(5, E), (7, B), (10, B), (11, D)]&lt;/code&gt; (re-ordered)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Iteration 3:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Extract Min:&lt;/strong&gt; &lt;code&gt;(5, E)&lt;/code&gt; is extracted. &lt;code&gt;dist[E]&lt;/code&gt; is finalized to 5.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark Visited:&lt;/strong&gt; &lt;code&gt;visited = {A, C, E}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Relax Neighbors of E:&lt;/strong&gt; (E has no unvisited neighbors in this example that would improve paths).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dist = {A: 0, B: 7, C: 3, D: 11, E: 5}&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;priority_queue = [(7, B), (10, B), (11, D)]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Iteration 4:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Extract Min:&lt;/strong&gt; &lt;code&gt;(7, B)&lt;/code&gt; is extracted. &lt;code&gt;dist[B]&lt;/code&gt; is finalized to 7. (The &lt;code&gt;(10, B)&lt;/code&gt; entry remains in the PQ but will be ignored if &lt;code&gt;B&lt;/code&gt; is already visited).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark Visited:&lt;/strong&gt; &lt;code&gt;visited = {A, C, E, B}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Relax Neighbors of B:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Neighbor D: &lt;code&gt;new_distance = dist[B] + weight(B, D) = 7 + 2 = 9&lt;/code&gt;. Since &lt;code&gt;9 &amp;lt; dist[D]&lt;/code&gt; (11), update &lt;code&gt;dist[D] = 9&lt;/code&gt;, &lt;code&gt;prev[D] = B&lt;/code&gt;. Add &lt;code&gt;(9, D)&lt;/code&gt; to PQ.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;dist = {A: 0, B: 7, C: 3, D: 9, E: 5}&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;priority_queue = [(9, D), (10, B), (11, D)]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Iteration 5:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Extract Min:&lt;/strong&gt; &lt;code&gt;(9, D)&lt;/code&gt; is extracted. &lt;code&gt;dist[D]&lt;/code&gt; is finalized to 9.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark Visited:&lt;/strong&gt; &lt;code&gt;visited = {A, C, E, B, D}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Relax Neighbors of D:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Neighbor E: &lt;code&gt;new_distance = dist[D] + weight(D, E) = 9 + 5 = 14&lt;/code&gt;. Since &lt;code&gt;14&lt;/code&gt; is NOT &lt;code&gt;&amp;lt; dist[E]&lt;/code&gt; (5), no update.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;dist = {A: 0, B: 7, C: 3, D: 9, E: 5}&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;priority_queue = [(10, B), (11, D)]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The priority queue now only contains entries for nodes already visited with higher path costs. The algorithm finishes when the priority queue is empty or contains only nodes with distances already finalized (if we explicitly check for &lt;code&gt;visited&lt;/code&gt; status before processing).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Final Distances:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A: 0&lt;/li&gt;
&lt;li&gt;B: 7 (A -&amp;gt; C -&amp;gt; B)&lt;/li&gt;
&lt;li&gt;C: 3 (A -&amp;gt; C)&lt;/li&gt;
&lt;li&gt;D: 9 (A -&amp;gt; C -&amp;gt; B -&amp;gt; D)&lt;/li&gt;
&lt;li&gt;E: 5 (A -&amp;gt; C -&amp;gt; E)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Paths (reconstructed using &lt;code&gt;prev&lt;/code&gt; array):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Path A to B: A -&amp;gt; C -&amp;gt; B&lt;/li&gt;
&lt;li&gt;Path A to C: A -&amp;gt; C&lt;/li&gt;
&lt;li&gt;Path A to D: A -&amp;gt; C -&amp;gt; B -&amp;gt; D&lt;/li&gt;
&lt;li&gt;Path A to E: A -&amp;gt; C -&amp;gt; E&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This step-by-step process highlights how Dijkstra's algorithm systematically finds the shortest paths by always expanding from the closest unvisited node.&lt;/p&gt;
&lt;h2 id="key-components-and-features"&gt;Key Components and Features&lt;/h2&gt;
&lt;p&gt;Understanding the operational details requires familiarity with the primary data structures and concepts Dijkstra's algorithm relies upon. These elements are not just implementation details; they are fundamental to its efficiency and correctness.&lt;/p&gt;
&lt;h3 id="graph-representation"&gt;Graph Representation&lt;/h3&gt;
&lt;p&gt;Dijkstra's algorithm operates on a graph, which is a collection of vertices (nodes) and edges (connections) between them. The edges typically have weights, representing distance, cost, time, or any other quantifiable metric.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Common Representations:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Adjacency Matrix:&lt;/strong&gt; A 2D array where &lt;code&gt;matrix[i][j]&lt;/code&gt; stores the weight of the edge from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt;. If no edge exists, a sentinel value (e.g., infinity) is used. This is suitable for dense graphs (many edges).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Adjacency List:&lt;/strong&gt; An array of lists (or dictionaries). &lt;code&gt;list[i]&lt;/code&gt; contains all neighbors of vertex &lt;code&gt;i&lt;/code&gt; along with their respective edge weights. This is generally more memory-efficient for sparse graphs (few edges), which are common in real-world scenarios. For Dijkstra's, adjacency lists are usually preferred for their efficiency in iterating through neighbors.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="priority-queue"&gt;Priority Queue&lt;/h3&gt;
&lt;p&gt;The priority queue is the linchpin of Dijkstra's algorithm's performance. It allows for the efficient retrieval of the node with the smallest known distance from the source that has not yet been processed. Without it, the algorithm would degrade significantly in efficiency.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How it works:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Stores &lt;code&gt;(distance, node)&lt;/code&gt; pairs.&lt;/li&gt;
&lt;li&gt;Always returns the pair with the minimum &lt;code&gt;distance&lt;/code&gt; value.&lt;/li&gt;
&lt;li&gt;Commonly implemented using a &lt;strong&gt;min-heap&lt;/strong&gt;, which offers &lt;code&gt;O(log V)&lt;/code&gt; time complexity for &lt;code&gt;insert&lt;/code&gt; and &lt;code&gt;extract_min&lt;/code&gt; operations, where &lt;code&gt;V&lt;/code&gt; is the number of vertices.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="non-negative-edge-weights-constraint"&gt;Non-Negative Edge Weights Constraint&lt;/h3&gt;
&lt;p&gt;A critical feature and limitation of Dijkstra's algorithm is its requirement for non-negative edge weights. This means that all edge weights must be zero or positive.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why this constraint?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If negative edge weights were allowed, Dijkstra's greedy approach could fail. Consider a path A -&amp;gt; B -&amp;gt; C, where A -&amp;gt; B has weight 5, and B -&amp;gt; C has weight -3. If Dijkstra's extracts B and finalizes its path, then later finds a path A -&amp;gt; D -&amp;gt; B with a total cost of 1, it cannot update the already finalized path to B, nor the path to C that went through B. Negative cycles (a path from a node back to itself with a total negative weight) would lead to an infinite loop, as the path could continuously get "shorter" by traversing the cycle. For graphs with negative edge weights, algorithms like Bellman-Ford are necessary.&lt;/p&gt;
&lt;h2 id="time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the computational cost of an algorithm is crucial for predicting its performance and suitability for various applications. Dijkstra's algorithm's complexity depends heavily on the graph representation and the priority queue implementation.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;Let &lt;code&gt;V&lt;/code&gt; be the number of vertices and &lt;code&gt;E&lt;/code&gt; be the number of edges in the graph.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; Setting up the &lt;code&gt;dist&lt;/code&gt; array and priority queue takes &lt;code&gt;O(V)&lt;/code&gt; time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Main Loop:&lt;/strong&gt; The loop runs &lt;code&gt;V&lt;/code&gt; times, as each vertex is extracted from the priority queue and finalized exactly once.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Inside the Loop:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Extract Min:&lt;/strong&gt; Each &lt;code&gt;extract_min&lt;/code&gt; operation from the priority queue takes &lt;code&gt;O(log V)&lt;/code&gt; time (for a binary heap). Since there are &lt;code&gt;V&lt;/code&gt; such operations, this contributes &lt;code&gt;O(V log V)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edge Relaxation:&lt;/strong&gt; For each vertex &lt;code&gt;u&lt;/code&gt; extracted, we iterate through its &lt;code&gt;degree(u)&lt;/code&gt; neighbors. In the worst case, we might insert an edge into the priority queue for each relaxation. An edge &lt;code&gt;(u, v)&lt;/code&gt; can cause an &lt;code&gt;insert&lt;/code&gt; or &lt;code&gt;decrease-key&lt;/code&gt; operation (if the priority queue supports it) into the priority queue. There are &lt;code&gt;E&lt;/code&gt; edges in total. Each of these operations takes &lt;code&gt;O(log V)&lt;/code&gt; time. So, this contributes &lt;code&gt;O(E log V)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Total Time Complexity:&lt;/strong&gt; &lt;code&gt;O(V log V + E log V)&lt;/code&gt; which simplifies to &lt;code&gt;O(E log V)&lt;/code&gt; since &lt;code&gt;E&lt;/code&gt; is typically much larger than &lt;code&gt;V&lt;/code&gt; in connected graphs (at least &lt;code&gt;V-1&lt;/code&gt; edges). In dense graphs, &lt;code&gt;E&lt;/code&gt; can be up to &lt;code&gt;V^2&lt;/code&gt;, making it &lt;code&gt;O(V^2 log V)&lt;/code&gt;. For a sparse graph (where &lt;code&gt;E&lt;/code&gt; is proportional to &lt;code&gt;V&lt;/code&gt;), it becomes &lt;code&gt;O(V log V)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Special Case: Using an Adjacency Matrix and a simple array to find min:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you don't use a priority queue and instead scan the &lt;code&gt;dist&lt;/code&gt; array to find the minimum distance node in each iteration, the "extract min" step would take &lt;code&gt;O(V)&lt;/code&gt; time. Since this is done &lt;code&gt;V&lt;/code&gt; times, it contributes &lt;code&gt;O(V^2)&lt;/code&gt;. The relaxation step then takes &lt;code&gt;O(E)&lt;/code&gt; over all iterations. The total complexity becomes &lt;code&gt;O(V^2 + E)&lt;/code&gt;. For dense graphs, this is &lt;code&gt;O(V^2)&lt;/code&gt;, which can be competitive with the priority queue approach. However, for sparse graphs, &lt;code&gt;O(E log V)&lt;/code&gt; is superior.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Fibonacci Heap Optimization:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Using a Fibonacci heap (a more complex priority queue structure) can theoretically reduce the time complexity to &lt;code&gt;O(E + V log V)&lt;/code&gt;. However, the constant factors involved in Fibonacci heaps are large, making them less practical than binary heaps for most common use cases unless the graph is extremely large and sparse.&lt;/p&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;The space complexity is determined by the data structures used:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Adjacency List:&lt;/strong&gt; &lt;code&gt;O(V + E)&lt;/code&gt; to store the graph.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;dist&lt;/code&gt; Array:&lt;/strong&gt; &lt;code&gt;O(V)&lt;/code&gt; to store distances.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;prev&lt;/code&gt; Array:&lt;/strong&gt; &lt;code&gt;O(V)&lt;/code&gt; to store predecessors (for path reconstruction).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Priority Queue:&lt;/strong&gt; In the worst case, it can hold up to &lt;code&gt;E&lt;/code&gt; entries (if &lt;code&gt;decrease-key&lt;/code&gt; isn't used and multiple entries for the same node exist). So, &lt;code&gt;O(E)&lt;/code&gt; space.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Total Space Complexity:&lt;/strong&gt; &lt;code&gt;O(V + E)&lt;/code&gt;. This is generally considered efficient, as it scales linearly with the size of the input graph.&lt;/p&gt;
&lt;h2 id="real-world-applications-of-dijkstras-algorithm"&gt;Real-World Applications of Dijkstra's Algorithm&lt;/h2&gt;
&lt;p&gt;Dijkstra's algorithm is not merely an academic exercise; it's a fundamental algorithm that underpins a vast array of real-world applications, silently powering many of the services we use daily. Its ability to find optimal paths efficiently makes it invaluable.&lt;/p&gt;
&lt;h3 id="1-gps-and-navigation-systems"&gt;1. GPS and Navigation Systems&lt;/h3&gt;
&lt;p&gt;Perhaps the most ubiquitous application, every time you use Google Maps, Apple Maps, or a standalone GPS device, Dijkstra's algorithm (or a variant like &lt;a href="/understanding-a-star-search-pathfinding-algorithm-tutorial/"&gt;A*&lt;/a&gt;, which builds upon Dijkstra's) is working behind the scenes. It calculates the shortest (or fastest, or least traffic-congested) route from your current location to your destination. The road network is modeled as a graph, with intersections as nodes and road segments as edges, where edge weights represent distance, time, or even real-time traffic data.&lt;/p&gt;
&lt;h3 id="2-network-routing-protocols"&gt;2. Network Routing Protocols&lt;/h3&gt;
&lt;p&gt;The internet itself relies heavily on shortest path algorithms. Routers use protocols like OSPF (Open Shortest Path First) to determine the most efficient paths for data packets to travel across the network. Each router builds a shortest path tree of the network topology, ensuring that data reaches its destination with minimal latency and hops. The network is a graph, routers are nodes, and connections are edges with weights representing link costs or latency.&lt;/p&gt;
&lt;h3 id="3-telecommunication-networks"&gt;3. Telecommunication Networks&lt;/h3&gt;
&lt;p&gt;Designing and optimizing telecommunication networks (e.g., fiber optic cable layouts, cellular network towers) requires finding the most cost-effective ways to connect different locations. Dijkstra's algorithm helps identify the shortest cable runs or the most efficient signal paths to minimize infrastructure costs and maximize network performance.&lt;/p&gt;
&lt;h3 id="4-logistics-and-supply-chain-management"&gt;4. Logistics and Supply Chain Management&lt;/h3&gt;
&lt;p&gt;Companies like Amazon, FedEx, and UPS leverage shortest path algorithms to optimize delivery routes for their fleets. Minimizing travel distance and time directly translates to fuel savings, faster deliveries, and reduced operational costs. Warehouses, distribution centers, and customer locations are nodes, and transport links are edges.&lt;/p&gt;
&lt;h3 id="5-urban-planning-and-transportation"&gt;5. Urban Planning and Transportation&lt;/h3&gt;
&lt;p&gt;City planners use graph theory and shortest path algorithms to analyze traffic flow, plan public transport routes, and optimize emergency service deployment. Identifying bottlenecks and designing efficient urban networks is crucial for minimizing congestion and improving quality of life.&lt;/p&gt;
&lt;h3 id="6-social-network-analysis"&gt;6. Social Network Analysis&lt;/h3&gt;
&lt;p&gt;While not directly for pathfinding in the traditional sense, Dijkstra's (and related algorithms) can be used to understand "degrees of separation" between individuals in social networks. If edge weights represent connection strength or similarity, it can find the strongest or most influential path between two people.&lt;/p&gt;
&lt;h3 id="7-game-development-ai-pathfinding"&gt;7. Game Development (AI Pathfinding)&lt;/h3&gt;
&lt;p&gt;In video games, non-player characters (NPCs) often need to find the shortest path to a target, navigate a complex environment, or pursue a player. The game world is often represented as a grid or a navigation mesh, which can be treated as a graph, and Dijkstra's or A* is used for efficient character movement.&lt;/p&gt;
&lt;h3 id="8-image-processing"&gt;8. Image Processing&lt;/h3&gt;
&lt;p&gt;Sometimes, Dijkstra's can be adapted for image segmentation, especially in medical imaging. Pixels or regions can be nodes, and edge weights represent the similarity or dissimilarity between adjacent regions. Finding a "shortest path" can define boundaries or segment objects within an image.&lt;/p&gt;
&lt;p&gt;The versatility of Dijkstra's algorithm stems from its fundamental nature in solving a core problem across diverse domains. Its ability to guarantee the optimal solution for its problem space makes it a go-to choice for developers and researchers alike.&lt;/p&gt;
&lt;h2 id="pros-and-cons-of-dijkstras-algorithm"&gt;Pros and Cons of Dijkstra's Algorithm&lt;/h2&gt;
&lt;p&gt;Like any powerful tool, Dijkstra's algorithm comes with a set of advantages and limitations that dictate its suitability for particular problems. A clear understanding of these helps in choosing the right algorithm for a given task.&lt;/p&gt;
&lt;h3 id="advantages-pros"&gt;Advantages (Pros)&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Guaranteed Optimality:&lt;/strong&gt; For graphs with non-negative edge weights, Dijkstra's algorithm is guaranteed to find the shortest path from the source to all other reachable nodes. This is a strong mathematical guarantee, making it highly reliable.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Versatility:&lt;/strong&gt; As demonstrated by its myriad applications, it's incredibly versatile. It forms the basis for many other algorithms (like A*) and is adaptable to various problem domains where shortest paths are needed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Well-Understood and Established:&lt;/strong&gt; Being one of the oldest and most widely studied graph algorithms, its behavior, complexity, and nuances are extremely well-documented. This makes it easier to implement, debug, and reason about.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficiency with Priority Queue:&lt;/strong&gt; When implemented with an efficient priority queue (like a binary heap), its time complexity of &lt;code&gt;O(E log V)&lt;/code&gt; (or &lt;code&gt;O(V log V + E)&lt;/code&gt; with Fibonacci heap) is very good for sparse graphs, which are common in real-world networks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Single-Source to All Destinations:&lt;/strong&gt; It inherently finds the shortest path from a single source to &lt;em&gt;all&lt;/em&gt; other nodes, which is often more efficient than running a single-destination algorithm multiple times for different targets.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="disadvantages-cons"&gt;Disadvantages (Cons)&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Non-Negative Edge Weights Constraint:&lt;/strong&gt; This is its most significant limitation. It cannot handle graphs with negative edge weights or negative cycles. If such edges exist, the algorithm might produce incorrect results or loop indefinitely (in the case of negative cycles). For these scenarios, algorithms like Bellman-Ford or SPFA are required.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Less Efficient for Negative Cycles:&lt;/strong&gt; Although the non-negative weight constraint means it generally won't encounter negative cycles, if one were to accidentally exist in an input dataset that Dijkstra's is applied to, it would fail to detect it and produce incorrect results, unlike Bellman-Ford which can detect such cycles.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Can be Slower for Dense Graphs (without optimization):&lt;/strong&gt; While &lt;code&gt;O(E log V)&lt;/code&gt; is good for sparse graphs, if the graph is dense (E approaches V^2), &lt;code&gt;O(V^2 log V)&lt;/code&gt; can become quite slow. A &lt;code&gt;O(V^2)&lt;/code&gt; array-based implementation might be faster in such cases due to better constant factors and cache locality, but still, this is worse than algorithms like Floyd-Warshall for all-pairs shortest paths in dense graphs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Explores Unnecessarily:&lt;/strong&gt; For finding the shortest path between just two specific nodes (&lt;code&gt;source&lt;/code&gt; and &lt;code&gt;destination&lt;/code&gt;), Dijkstra's algorithm might explore large parts of the graph that are not on the optimal path to the destination. While it stops once the destination is extracted from the priority queue, it still processes more nodes than a goal-directed search algorithm like A* in many cases.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Does Not Benefit from Heuristics:&lt;/strong&gt; Unlike A*, Dijkstra's is an uninformed search algorithm. It doesn't use any heuristic information about the distance to the target node. This means it explores nodes purely based on their accumulated path cost from the source, rather than trying to prioritize nodes that seem "closer" to the destination.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Despite its limitations, Dijkstra's algorithm remains a cornerstone of computer science due to its widespread applicability and guaranteed correctness under its specified conditions. The key is to correctly identify whether a given problem fits these conditions.&lt;/p&gt;
&lt;h2 id="related-algorithms-and-comparison"&gt;Related Algorithms and Comparison&lt;/h2&gt;
&lt;p&gt;Dijkstra's algorithm is a cornerstone, but it's not the only player in the field of shortest path problems. Understanding how it compares to its brethren provides a more complete picture of graph theory.&lt;/p&gt;
&lt;h3 id="bellman-ford-algorithm"&gt;Bellman-Ford Algorithm&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Key Difference:&lt;/strong&gt; Bellman-Ford can handle graphs with &lt;strong&gt;negative edge weights&lt;/strong&gt;, as long as there are no negative cycles reachable from the source. It can also detect the presence of negative cycles.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; Instead of a greedy approach with a priority queue, Bellman-Ford uses &lt;a href="/dynamic-programming-breaking-down-complex-problems/"&gt;dynamic programming&lt;/a&gt;. It relaxes all edges &lt;code&gt;V-1&lt;/code&gt; times, ensuring that the shortest path of &lt;code&gt;k&lt;/code&gt; edges is found after the &lt;code&gt;k&lt;/code&gt;-th iteration. If a path can still be relaxed after &lt;code&gt;V-1&lt;/code&gt; iterations, a negative cycle exists.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; &lt;code&gt;O(V * E)&lt;/code&gt;. This is generally worse than Dijkstra's &lt;code&gt;O(E log V)&lt;/code&gt; for sparse graphs but better for graphs with negative weights.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt; When negative edge weights are present, such as in financial arbitrage problems or network routing scenarios where "cost" can represent a gain.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="a-search-algorithm"&gt;A* Search Algorithm&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Key Difference:&lt;/strong&gt; A&lt;em&gt; is an &lt;/em&gt;&lt;em&gt;informed search algorithm&lt;/em&gt;* that extends Dijkstra's by incorporating a heuristic function &lt;code&gt;h(n)&lt;/code&gt; which estimates the cost from the current node &lt;code&gt;n&lt;/code&gt; to the target node. It prioritizes nodes based on &lt;code&gt;f(n) = g(n) + h(n)&lt;/code&gt;, where &lt;code&gt;g(n)&lt;/code&gt; is the actual cost from the source to &lt;code&gt;n&lt;/code&gt; (Dijkstra's part), and &lt;code&gt;h(n)&lt;/code&gt; is the estimated cost from &lt;code&gt;n&lt;/code&gt; to the target.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; Uses a priority queue like Dijkstra's, but the priority is &lt;code&gt;f(n)&lt;/code&gt; instead of just &lt;code&gt;g(n)&lt;/code&gt;. The heuristic &lt;code&gt;h(n)&lt;/code&gt; must be "admissible" (never overestimates the actual cost to the goal) and often "consistent" for A* to guarantee optimality.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; Can be significantly faster than Dijkstra's, especially in large graphs, as it intelligently prunes the search space by guiding the search towards the goal. In the worst case, it can degrade to &lt;code&gt;O(E log V)&lt;/code&gt; or even &lt;code&gt;O(V^2)&lt;/code&gt; if the heuristic is poor.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt; Ideal for single-source, single-destination shortest path problems, particularly in grid-based maps (like game AI pathfinding) or situations where a good heuristic is available (e.g., Euclidean distance in geometric problems).&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="floyd-warshall-algorithm"&gt;Floyd-Warshall Algorithm&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Key Difference:&lt;/strong&gt; This algorithm solves the &lt;strong&gt;all-pairs shortest path problem&lt;/strong&gt;, meaning it finds the shortest path between &lt;em&gt;every&lt;/em&gt; pair of nodes in the graph.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; Uses dynamic programming. It iteratively tries to improve the shortest path between two nodes &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;j&lt;/code&gt; by considering all possible intermediate nodes &lt;code&gt;k&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; &lt;code&gt;O(V^3)&lt;/code&gt;. It's a cubic algorithm, so it's less efficient for single-source problems than Dijkstra's or Bellman-Ford but superior for small-to-medium sized dense graphs when all-pairs shortest paths are needed.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt; When you need the shortest path between any two points, for example, in routing tables where every node needs to know the shortest path to every other node.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="prims-algorithm-and-kruskals-algorithm"&gt;Prim's Algorithm and Kruskal's Algorithm&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Key Difference:&lt;/strong&gt; These algorithms are for finding a &lt;strong&gt;Minimum Spanning Tree (MST)&lt;/strong&gt;, not shortest paths. An MST connects all vertices in a graph with the minimum possible total edge weight, but the path between any two nodes in an MST is not necessarily the shortest path between those nodes in the original graph.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; Prim's is similar to Dijkstra's in its greedy "grow a tree" approach using a priority queue. Kruskal's uses a disjoint-set data structure to connect components.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt; Network design, cluster analysis, electrical circuit design, where connecting all components with minimum cost is the goal.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In summary, while Dijkstra's algorithm is excellent for single-source shortest paths in graphs with non-negative weights, the choice of algorithm depends critically on the specific problem constraints: the presence of negative weights, whether a heuristic is available, and whether all-pairs or single-source shortest paths are needed.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="future-outlook-and-advanced-considerations"&gt;Future Outlook and Advanced Considerations&lt;/h2&gt;
&lt;p&gt;The foundational principles of Dijkstra's algorithm, while established, continue to evolve in modern computing. As graphs become massive – think the internet's scale, or global social networks – and real-time demands intensify, pure Dijkstra's often requires augmentation or entirely new paradigms.&lt;/p&gt;
&lt;h3 id="large-scale-graphs-and-performance-optimization"&gt;Large-Scale Graphs and Performance Optimization&lt;/h3&gt;
&lt;p&gt;For extremely large graphs, plain Dijkstra's can be too slow. Several optimizations and variations are actively researched and implemented:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Bidirectional Dijkstra:&lt;/strong&gt; Runs two Dijkstra's searches simultaneously, one from the source and one from the destination, meeting somewhere in the middle. This can significantly reduce the search space, especially if the graph is relatively uniform.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ALT Algorithm (A*, Landmarks, Triangle inequality):&lt;/strong&gt; Combines A* with precomputed distances to "landmarks" to create highly effective heuristics, dramatically speeding up queries on static graphs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Contraction Hierarchies:&lt;/strong&gt; A preprocessing technique that shortcuts paths through "important" nodes, creating a hierarchical graph representation. Querying on this contracted graph is much faster, often yielding real-time performance on continental road networks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Parallel and Distributed Algorithms:&lt;/strong&gt; For truly massive graphs that don't fit into a single machine's memory, Dijkstra's can be adapted for parallel processing (e.g., using GPUs) or distributed systems (e.g., Apache Giraph, GraphX) to leverage multiple computing resources.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="dynamic-graphs"&gt;Dynamic Graphs&lt;/h3&gt;
&lt;p&gt;Many real-world graphs are dynamic, meaning their structure (nodes or edges) or edge weights change over time. Think real-time traffic updates in a navigation system. Standard Dijkstra's has to recompute the entire path from scratch for every change, which is inefficient.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Dynamic Shortest Path Algorithms:&lt;/strong&gt; Research in this area focuses on incrementally updating shortest paths efficiently when changes occur, rather than full recomputation. This includes algorithms like Reachability queries and various incremental graph algorithms.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Event-Driven Systems:&lt;/strong&gt; In navigation, events like traffic jams or road closures trigger updates, and dynamic algorithms help reassess routes quickly.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="probabilistic-and-stochastic-shortest-paths"&gt;Probabilistic and Stochastic Shortest Paths&lt;/h3&gt;
&lt;p&gt;In some scenarios, edge weights are not fixed but are probabilities or random variables (e.g., travel time through an intersection can vary based on time of day or traffic light cycles).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Stochastic Shortest Path Problems:&lt;/strong&gt; These problems seek paths that minimize expected travel time or maximize the probability of arrival within a certain timeframe. These often involve more complex mathematical models (e.g., Markov Decision Processes) than standard Dijkstra's.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="quantum-computing-and-graph-algorithms"&gt;Quantum Computing and Graph Algorithms&lt;/h3&gt;
&lt;p&gt;While still in its nascent stages, quantum computing poses a potential future direction for certain types of graph problems. Algorithms like quantum search (Grover's algorithm) might offer quadratic speedups for unstructured searches, and some theoretical frameworks are exploring how quantum annealing could tackle optimization problems on graphs, potentially including shortest path variants. However, practical quantum algorithms for general shortest path problems that outperform classical ones remain a significant challenge.&lt;/p&gt;
&lt;p&gt;The future of shortest path finding lies in algorithms that are increasingly adaptive, scalable, and capable of handling uncertainty and dynamic changes. While the core logic of Dijkstra's algorithm remains timeless, its practical implementations continue to evolve, integrating with machine learning, distributed systems, and advanced data structures to meet the demands of an ever-more interconnected and complex digital world. The journey of finding the shortest path is far from over.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;From navigating bustling city streets to routing data packets across continents, the problem of finding the shortest path is a foundational challenge in computer science and engineering. At the heart of many elegant solutions lies Dijkstra's Algorithm: Shortest Path Finding Explained in a manner that reveals its power. Its ingenious greedy approach, bolstered by the efficiency of priority queues, provides a robust and reliable method for determining optimal routes in graphs with non-negative edge weights.&lt;/p&gt;
&lt;p&gt;We've explored its step-by-step mechanics, illustrating how it systematically expands the shortest path from a source node, ensuring optimality. Understanding its time and space complexities (&lt;code&gt;O(E log V)&lt;/code&gt; with a binary heap) is crucial for assessing its performance in various scenarios. While indispensable, its limitation to non-negative edge weights necessitates the consideration of other algorithms like Bellman-Ford for different problem domains or A* for goal-directed searches.&lt;/p&gt;
&lt;p&gt;The widespread applicability of Dijkstra's algorithm, from GPS systems and network routing to logistics and even game AI, underscores its profound impact on modern technology. As we look to the future, research continues to refine and extend its principles to tackle increasingly complex and dynamic graph structures, ensuring that the quest for efficient pathfinding remains at the forefront of algorithmic innovation. Mastering Dijkstra's is not just about understanding an algorithm; it's about gaining a critical tool for solving some of the most pervasive optimization problems of our time.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is Dijkstra's Algorithm used for?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Dijkstra's Algorithm is primarily used to find the shortest paths between nodes in a graph, from a single source node to all other reachable nodes. It's fundamental for GPS navigation, network routing protocols, logistics, and game AI pathfinding.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the main limitation of Dijkstra's Algorithm?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Its main limitation is that it cannot handle graphs with negative edge weights. The algorithm assumes that all edge weights are non-negative, and its greedy approach fails to find correct shortest paths if negative weights are present.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: How does Dijkstra's Algorithm work conceptually?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: It works by iteratively exploring unvisited nodes, always selecting the node with the smallest known distance from the source. It then updates the distances of its neighbors if a shorter path is found through the current node, using a priority queue to efficiently manage node selection.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm"&gt;Dijkstra's Algorithm on Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.amazon.com/Introduction-Algorithms-Thomas-H-Cormen/dp/0262033844"&gt;Introduction to Algorithms (CLRS) - Chapter on Shortest Paths&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/"&gt;GeeksforGeeks: Dijkstra's Shortest Path Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.cs.usfca.edu/~galles/visualization/Dijkstra.html"&gt;Visualizing Dijkstra's Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Graph Theory"/><category term="Competitive Programming"/><category term="LeetCode"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/dijkstras-algorithm-shortest-path-explained.webp" width="1200"/><media:title type="plain">Dijkstra's Algorithm: Shortest Path Finding Explained In Depth</media:title><media:description type="plain">Demystify Dijkstra's Algorithm, the core of shortest path finding. Explore its mechanics, applications, and complexity, powering navigation and network routing.</media:description></entry><entry><title>Understanding A* Search: Pathfinding Algorithm Tutorial</title><link href="https://analyticsdrive.tech/understanding-a-star-search-pathfinding-algorithm-tutorial/" rel="alternate"/><published>2026-03-23T00:55:00+05:30</published><updated>2026-03-23T00:55:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-23:/understanding-a-star-search-pathfinding-algorithm-tutorial/</id><summary type="html">&lt;p&gt;Explore Understanding A* Search, a critical pathfinding algorithm. Learn its mechanics, key components, and real-world applications in AI, robotics, and gaming.&lt;/p&gt;</summary><content type="html">&lt;p&gt;To efficiently navigate complex digital landscapes, from video game maps to robotic pathways, &lt;strong&gt;understanding A* Search&lt;/strong&gt;, a powerful &lt;strong&gt;pathfinding algorithm&lt;/strong&gt;, is crucial. At the heart of many such systems lies a widely adopted technique: the A* search algorithm. This comprehensive &lt;strong&gt;Understanding A* Search: Pathfinding Algorithm Tutorial&lt;/strong&gt; will demystify one of the most celebrated graph traversal and pathfinding algorithms, exploring its mechanics, underlying principles, and the reasons behind its enduring popularity in computing. Whether you're a budding AI developer, a game designer, or simply a tech enthusiast keen to understand advanced algorithms, this guide promises a deep dive into its fascinating world.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-a-search-the-intelligent-navigator"&gt;What is A* Search? The Intelligent Navigator&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#a-brief-history-of-informed-search"&gt;A Brief History of Informed Search&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#how-a-search-works-the-core-mechanics"&gt;How A* Search Works: The Core Mechanics&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-evaluation-function-fn-gn-hn"&gt;The Evaluation Function: f(n) = g(n) + h(n)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-by-step-algorithm-walkthrough"&gt;Step-by-Step Algorithm Walkthrough&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#pseudocode-for-a-search"&gt;Pseudocode for A* Search&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#key-components-of-a-search"&gt;Key Components of A* Search&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-graph-representation"&gt;The Graph Representation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#cost-function-gn-the-path-so-far"&gt;Cost Function: g(n) - The Path So Far&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#heuristic-function-hn-the-educated-guess"&gt;Heuristic Function: h(n) - The Educated Guess&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#evaluation-function-fn-the-guiding-star"&gt;Evaluation Function: f(n) - The Guiding Star&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#open-and-closed-lists"&gt;Open and Closed Lists&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-a-search-performance-and-complexity"&gt;Understanding A* Search: Performance and Complexity&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#comparison-with-other-algorithms"&gt;Comparison with Other Algorithms&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-a-search"&gt;Real-World Applications of A* Search&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-video-game-artificial-intelligence-ai"&gt;1. Video Game Artificial Intelligence (AI)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-robotics-and-autonomous-navigation"&gt;2. Robotics and Autonomous Navigation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-logistics-and-transportation"&gt;3. Logistics and Transportation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-network-routing"&gt;4. Network Routing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-artificial-intelligence-planning"&gt;5. Artificial Intelligence Planning&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#advantages-and-limitations-of-a-search"&gt;Advantages and Limitations of A* Search&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#advantages-of-a-search"&gt;Advantages of A* Search&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#limitations-of-a-search"&gt;Limitations of A* Search&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#optimizations-and-variants-of-a-search"&gt;Optimizations and Variants of A* Search&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-iterative-deepening-a-ida"&gt;1. Iterative Deepening A (IDA)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-memory-bounded-a-ma-sma"&gt;2. Memory-Bounded A (MA, SMA*)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-jump-point-search-jps"&gt;3. Jump Point Search (JPS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-theta-and-any-angle-pathfinding"&gt;4. Theta* and Any-Angle Pathfinding&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-hierarchical-a-hna"&gt;5. Hierarchical A (HNA)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-future-outlook-of-pathfinding-and-a"&gt;The Future Outlook of Pathfinding and A*&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#integration-with-machine-learning"&gt;Integration with Machine Learning&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#pathfinding-in-multi-agent-systems"&gt;Pathfinding in Multi-Agent Systems&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#quantum-computings-potential"&gt;Quantum Computing's Potential&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#human-ai-collaboration-in-pathfinding"&gt;Human-AI Collaboration in Pathfinding&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id="what-is-a-search-the-intelligent-navigator"&gt;What is A* Search? The Intelligent Navigator&lt;/h2&gt;
&lt;p&gt;A* search (pronounced "A-star search") stands as a cornerstone in the field of artificial intelligence and computer science, particularly for problems requiring optimal pathfinding in graphs or grid-based environments. Conceived in 1968 by Peter Hart, Nils Nilsson, and Bertram Raphael at Stanford Research Institute, it quickly surpassed its predecessors by combining the completeness and optimality of Dijkstra's algorithm with the speed advantage of greedy best-first search. A* is essentially an informed search algorithm, meaning it leverages problem-specific heuristic information to guide its search, making it significantly more efficient than uninformed search methods like Breadth-First Search (BFS) or Depth-First Search (DFS) for many real-world scenarios.&lt;/p&gt;
&lt;p&gt;At its core, A* aims to find the shortest path from a specified start node to a specified goal node within a graph. What sets it apart is its ingenious evaluation function, which estimates the total cost of a path through a particular node. This function considers both the cost incurred from the start node to the current node and an estimated cost from the current node to the goal node. By prioritizing nodes that appear to be closer to the destination, A* intelligently prunes vast sections of the search space, arriving at the optimal solution with remarkable efficiency.&lt;/p&gt;
&lt;h3 id="a-brief-history-of-informed-search"&gt;A Brief History of Informed Search&lt;/h3&gt;
&lt;p&gt;Before A*, algorithms like Dijkstra's could find the shortest path, but they did so by exploring outward in all directions, often unnecessarily examining nodes far from the direct route to the goal. Greedy Best-First Search, on the other hand, uses only a heuristic to estimate distance to the goal, quickly finding a path but not always the optimal one. A* emerged as a hybrid solution, taking the best attributes of both. Its development marked a significant leap, providing a robust framework for navigation systems that require both speed and guaranteed optimality.&lt;/p&gt;
&lt;h2 id="how-a-search-works-the-core-mechanics"&gt;How A* Search Works: The Core Mechanics&lt;/h2&gt;
&lt;p&gt;The operational principle of A* search is elegant yet powerful. It systematically explores potential paths, prioritizing those that seem most promising, until it guarantees the shortest possible route has been found. This "promising" nature is determined by a unique cost function.&lt;/p&gt;
&lt;p&gt;A* maintains two lists (often implemented as priority queues and &lt;a href="/what-is-a-hash-map-hashing-concepts/"&gt;hash sets&lt;/a&gt;):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Open List (or Open Set):&lt;/strong&gt;
    Contains nodes that have been discovered but not yet evaluated. These are candidates for the next step in the path. This list is typically implemented as a &lt;a href="/how-to-implement-binary-search-tree-python/"&gt;priority queue&lt;/a&gt; to efficiently retrieve the node with the lowest &lt;code&gt;f(n)&lt;/code&gt; value.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Closed List (or Closed Set):&lt;/strong&gt;
    Contains nodes that have already been evaluated. These nodes will not be revisited.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The algorithm proceeds iteratively, always selecting the node from the Open List that has the lowest total estimated cost &lt;code&gt;f(n)&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="the-evaluation-function-fn-gn-hn"&gt;The Evaluation Function: &lt;code&gt;f(n) = g(n) + h(n)&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The brilliance of A* lies in its evaluation function &lt;code&gt;f(n)&lt;/code&gt; for any given node &lt;code&gt;n&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;g(n)&lt;/code&gt;:&lt;/strong&gt;
    This represents the actual cost of the path from the starting node to node &lt;code&gt;n&lt;/code&gt;. It's the sum of edge weights encountered so far. When moving from one node to a neighbor, &lt;code&gt;g(n)&lt;/code&gt; for the neighbor is calculated as &lt;code&gt;g(current_node) + cost(current_node, neighbor)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;h(n)&lt;/code&gt;:&lt;/strong&gt;
    This is the heuristic function, which estimates the cost of the cheapest path from node &lt;code&gt;n&lt;/code&gt; to the goal node. This estimate &lt;em&gt;must&lt;/em&gt; be admissible (never overestimate the actual cost) to guarantee optimality. Common heuristics include Manhattan distance (for grid-based movement where only cardinal directions are allowed) or Euclidean distance (for any direction).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;f(n)&lt;/code&gt;:&lt;/strong&gt;
    The total estimated cost of the cheapest path from the start node to the goal node &lt;em&gt;that passes through node &lt;code&gt;n&lt;/code&gt;&lt;/em&gt;. By always choosing the node with the lowest &lt;code&gt;f(n)&lt;/code&gt; from the Open List, A* combines the certainty of &lt;code&gt;g(n)&lt;/code&gt; with the informed guess of &lt;code&gt;h(n)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-by-step-algorithm-walkthrough"&gt;Step-by-Step Algorithm Walkthrough&lt;/h3&gt;
&lt;p&gt;Let's break down the execution flow of the A* algorithm:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Add the starting node to the Open List.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;g(start_node) = 0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Calculate &lt;code&gt;h(start_node)&lt;/code&gt; using the chosen heuristic.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;f(start_node) = g(start_node) + h(start_node)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For all other nodes, initialize &lt;code&gt;g(n)&lt;/code&gt; to infinity.&lt;/li&gt;
&lt;li&gt;Keep track of where each node came from (parent pointer) to reconstruct the path later.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Iteration:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;While the Open List is not empty:&lt;ul&gt;
&lt;li&gt;Retrieve the node &lt;code&gt;current_node&lt;/code&gt; from the Open List that has the lowest &lt;code&gt;f(n)&lt;/code&gt; value.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;current_node&lt;/code&gt; is the goal node, reconstruct the path by following parent pointers from the goal back to the start, and terminate the algorithm. You've found the optimal path.&lt;/li&gt;
&lt;li&gt;Remove &lt;code&gt;current_node&lt;/code&gt; from the Open List and add it to the Closed List.&lt;/li&gt;
&lt;li&gt;For each neighbor &lt;code&gt;neighbor&lt;/code&gt; of &lt;code&gt;current_node&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;neighbor&lt;/code&gt; is already in the Closed List, ignore it (we've already found the best path to it).&lt;/li&gt;
&lt;li&gt;Calculate &lt;code&gt;tentative_g = g(current_node) + cost(current_node, neighbor)&lt;/code&gt;. This is the cost of reaching &lt;code&gt;neighbor&lt;/code&gt; through &lt;code&gt;current_node&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;tentative_g&lt;/code&gt; is less than &lt;code&gt;g(neighbor)&lt;/code&gt; (meaning we found a &lt;em&gt;better&lt;/em&gt; path to &lt;code&gt;neighbor&lt;/code&gt;):&lt;ul&gt;
&lt;li&gt;Set &lt;code&gt;g(neighbor) = tentative_g&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;parent(neighbor) = current_node&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Calculate &lt;code&gt;h(neighbor)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;f(neighbor) = g(neighbor) + h(neighbor)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;neighbor&lt;/code&gt; is not in the Open List, add it. If it is in the Open List, update its &lt;code&gt;f(n)&lt;/code&gt; value (which is automatically handled by a priority queue implementation).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Failure:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the Open List becomes empty and the goal node has not been reached, it means there is no path from the start to the goal.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="pseudocode-for-a-search"&gt;Pseudocode for A* Search&lt;/h3&gt;
&lt;p&gt;While the detailed implementation can be complex, the core logic can be summarized:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;function A_Star_Search(start, goal):
    open_set := a min-priority queue ordered by f_score
    closed_set := an empty set

    g_score := map with default infinity
    g_score[start] := 0

    f_score := map with default infinity
    f_score[start] := h(start)

    parent_map := map to store parent pointers

    add (f_score[start], start) to open_set

    while open_set is not empty:
        current := node in open_set with lowest f_score
        remove current from open_set
        add current to closed_set

        if current == goal:
            return reconstruct_path(parent_map, current)

        for each neighbor of current:
            if neighbor is in closed_set:
                continue

            tentative_g_score := g_score[current] + distance(current, neighbor)

            if tentative_g_score &amp;lt; g_score[neighbor]:
                parent_map[neighbor] := current
                g_score[neighbor] := tentative_g_score
                f_score[neighbor] := g_score[neighbor] + h(neighbor)
                if neighbor is not in open_set:
                    add (f_score[neighbor], neighbor) to open_set

    return failure (no path found)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This structured approach allows A* to explore the most promising paths first, quickly converging on the optimal solution.&lt;/p&gt;
&lt;h2 id="key-components-of-a-search"&gt;Key Components of A* Search&lt;/h2&gt;
&lt;p&gt;To truly appreciate the efficacy of A*, it's essential to dissect its fundamental building blocks. Each component plays a critical role in guiding the search towards an optimal path.&lt;/p&gt;
&lt;h3 id="the-graph-representation"&gt;The Graph Representation&lt;/h3&gt;
&lt;p&gt;Before any pathfinding can occur, the environment must be represented as a graph.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Vertices (Nodes):&lt;/strong&gt;
    These represent locations or states within the search space. In a game, these might be grid squares, intersections, or specific points of interest. In a transportation network, they could be cities or bus stops.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Edges (Links):&lt;/strong&gt;
    These connect vertices and represent possible transitions between locations or states. Each edge typically has an associated weight or cost, representing the effort, distance, or time required to traverse that edge.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;Graph Representation:
Vertices: (x,y) coordinates on a grid, cities, states
Edges: connections between (x,y) cells, roads between cities
Edge Weights: distance, time, fuel cost, difficulty
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="cost-function-gn-the-path-so-far"&gt;Cost Function: &lt;code&gt;g(n)&lt;/code&gt; - The Path So Far&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;g(n)&lt;/code&gt; value for a node &lt;code&gt;n&lt;/code&gt; quantifies the actual, accumulated cost from the start node to &lt;code&gt;n&lt;/code&gt;. It's a measure of how "expensive" it has been to reach &lt;code&gt;n&lt;/code&gt; from the origin.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt;
    &lt;code&gt;g(start_node)&lt;/code&gt; is always 0. All other &lt;code&gt;g(n)&lt;/code&gt; are initialized to infinity.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt;
    When A* considers moving from &lt;code&gt;current_node&lt;/code&gt; to &lt;code&gt;neighbor&lt;/code&gt;, it calculates &lt;code&gt;g(neighbor)&lt;/code&gt; as &lt;code&gt;g(current_node) + cost(current_node, neighbor)&lt;/code&gt;. If this new path to &lt;code&gt;neighbor&lt;/code&gt; is cheaper than any previously found path, &lt;code&gt;g(neighbor)&lt;/code&gt; is updated.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Importance:&lt;/strong&gt;
    &lt;code&gt;g(n)&lt;/code&gt; ensures that A* is always considering the &lt;em&gt;actual&lt;/em&gt; cost of the path discovered so far, which is crucial for guaranteeing optimality.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="heuristic-function-hn-the-educated-guess"&gt;Heuristic Function: &lt;code&gt;h(n)&lt;/code&gt; - The Educated Guess&lt;/h3&gt;
&lt;p&gt;The heuristic function &lt;code&gt;h(n)&lt;/code&gt; is the "informed" part of A*. It estimates the cost of the cheapest path from node &lt;code&gt;n&lt;/code&gt; to the goal node. The quality of the heuristic significantly impacts A*'s performance.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Admissibility:&lt;/strong&gt;
    A heuristic &lt;code&gt;h(n)&lt;/code&gt; is &lt;em&gt;admissible&lt;/em&gt; if it never overestimates the actual cost to reach the goal. That is, &lt;code&gt;h(n) &amp;lt;= actual_cost(n, goal)&lt;/code&gt; for all nodes &lt;code&gt;n&lt;/code&gt;. An admissible heuristic guarantees that A* will find the optimal path.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Example: For grid-based movement where movement is restricted to cardinal directions (no diagonals), the Manhattan distance is an admissible heuristic.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code&gt;text
Manhattan Distance: |x1 - x2| + |y1 - y2|&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Consistency (Monotonicity):&lt;/strong&gt;
    A heuristic &lt;code&gt;h(n)&lt;/code&gt; is &lt;em&gt;consistent&lt;/em&gt; if, for every node &lt;code&gt;n&lt;/code&gt; and every successor &lt;code&gt;n'&lt;/code&gt; of &lt;code&gt;n&lt;/code&gt;, the estimated cost &lt;code&gt;h(n)&lt;/code&gt; is less than or equal to the cost of moving from &lt;code&gt;n&lt;/code&gt; to &lt;code&gt;n'&lt;/code&gt; plus the estimated cost from &lt;code&gt;n'&lt;/code&gt; to the goal. That is, &lt;code&gt;h(n) &amp;lt;= cost(n, n') + h(n')&lt;/code&gt;. All consistent heuristics are also admissible. Consistency is a stronger condition and simplifies some aspects of the algorithm, particularly removing the need to re-add nodes to the Open List if a better path is found to them after they've been added to the Closed List.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Importance:&lt;/strong&gt;
    A good heuristic can dramatically reduce the number of nodes A* has to explore, speeding up the search. A poor (or non-admissible) heuristic might lead to non-optimal paths or only marginally improve performance over uninformed searches.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="evaluation-function-fn-the-guiding-star"&gt;Evaluation Function: &lt;code&gt;f(n)&lt;/code&gt; - The Guiding Star&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;f(n)&lt;/code&gt; value combines &lt;code&gt;g(n)&lt;/code&gt; and &lt;code&gt;h(n)&lt;/code&gt; to provide the total estimated cost of a path passing through &lt;code&gt;n&lt;/code&gt; to the goal.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;f(n) = g(n) + h(n)&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Role:&lt;/strong&gt;
    &lt;code&gt;f(n)&lt;/code&gt; is the priority key used to order nodes in the Open List. A* always expands the node with the lowest &lt;code&gt;f(n)&lt;/code&gt;, meaning it prioritizes paths that have been cheap so far &lt;em&gt;and&lt;/em&gt; are estimated to be cheap going forward. This balance is what makes A* so effective.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="open-and-closed-lists"&gt;Open and Closed Lists&lt;/h3&gt;
&lt;p&gt;These data structures are crucial for managing the search process:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Open List (Priority Queue):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Stores nodes that have been visited but whose neighbors have not yet been fully explored.&lt;/li&gt;
&lt;li&gt;Organized as a min-priority queue based on the &lt;code&gt;f(n)&lt;/code&gt; value, ensuring that the most promising node is always retrieved first.&lt;/li&gt;
&lt;li&gt;Think of it as the set of "frontier" nodes awaiting evaluation.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Closed List (Hash Set):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Stores nodes that have already been fully evaluated (i.e., removed from the Open List).&lt;/li&gt;
&lt;li&gt;Used to prevent the algorithm from re-evaluating nodes or falling into cycles.&lt;/li&gt;
&lt;li&gt;Nodes in the Closed List are considered finalized; their &lt;code&gt;g(n)&lt;/code&gt; value is assumed to be the optimal &lt;code&gt;g(n)&lt;/code&gt; found so far.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These components work in concert, allowing A* to efficiently prune the search space and zero in on the optimal path.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="understanding-a-search-performance-and-complexity"&gt;Understanding A* Search: Performance and Complexity&lt;/h2&gt;
&lt;p&gt;The efficiency of any algorithm is paramount, and A* search shines particularly brightly in its performance characteristics, especially when paired with an effective heuristic. Its time and space complexity are influenced by several factors, including the size and structure of the graph, the accuracy of the heuristic function, and the branching factor of the search space.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;The &lt;a href="/big-o-notation-explained-beginner-guide-complexity/"&gt;time complexity&lt;/a&gt; of A* search is typically expressed as &lt;code&gt;O(E + V log V)&lt;/code&gt; in the worst case for general graphs when using a priority queue for the open list, where &lt;code&gt;E&lt;/code&gt; is the number of edges and &lt;code&gt;V&lt;/code&gt; is the number of vertices. However, in practice, with a good heuristic, A* often performs much better.&lt;/p&gt;
&lt;p&gt;More precisely, for a graph with non-negative edge weights and an admissible heuristic:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Worst-case without a good heuristic:&lt;/strong&gt;
    The time complexity can be exponential, &lt;code&gt;O(b^d)&lt;/code&gt;, where &lt;code&gt;b&lt;/code&gt; is the branching factor and &lt;code&gt;d&lt;/code&gt; is the depth of the optimal solution. This occurs if the heuristic provides little to no guidance, forcing A* to explore a large portion of the state space, similar to Dijkstra's.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;With an effective (and admissible) heuristic:&lt;/strong&gt;
    The time complexity can be significantly reduced, sometimes even becoming polynomial &lt;code&gt;O(E)&lt;/code&gt; or &lt;code&gt;O(V log V)&lt;/code&gt; in specific graph types or with very strong heuristics. The better the heuristic (i.e., the closer &lt;code&gt;h(n)&lt;/code&gt; is to the true cost without overestimating), the faster A* will find the solution, as fewer nodes need to be explored.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Graph Density:&lt;/strong&gt;
    In dense graphs, where many connections exist, &lt;code&gt;E&lt;/code&gt; can be close to &lt;code&gt;V^2&lt;/code&gt;. In sparse graphs, &lt;code&gt;E&lt;/code&gt; is closer to &lt;code&gt;V&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;The space complexity of A* search is &lt;code&gt;O(V)&lt;/code&gt; in the worst case, as it needs to store all visited nodes in the Closed List and all frontier nodes in the Open List. In scenarios with extremely large state spaces, this can become a significant limitation. For example, if searching a very large grid map, storing every single node could exhaust available memory.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Dependency on Path Length:&lt;/strong&gt;
    The space complexity is directly proportional to the number of nodes explored, which can be &lt;code&gt;O(V)&lt;/code&gt; in the worst case. If the optimal path is very long, or the heuristic is weak, many nodes might need to be stored.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Impact of Heuristic:&lt;/strong&gt;
    A stronger heuristic reduces the number of nodes explored, thereby decreasing the memory footprint.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="comparison-with-other-algorithms"&gt;Comparison with Other Algorithms&lt;/h3&gt;
&lt;p&gt;To fully appreciate A*'s performance, it's useful to compare it to other pathfinding algorithms:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Dijkstra's Algorithm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pros:&lt;/strong&gt;
    Guarantees optimal path, works with any non-negative edge weights.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Cons:&lt;/strong&gt;
    Uninformed search, explores in all directions, can be slow for large graphs, especially when the goal is far away.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;A* vs. Dijkstra:&lt;/strong&gt;
    A* can be seen as a generalized Dijkstra's. If &lt;code&gt;h(n)&lt;/code&gt; is always 0, A* effectively becomes Dijkstra's algorithm. The heuristic guides A* directly towards the goal, avoiding unnecessary exploration.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Breadth-First Search (BFS):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pros:&lt;/strong&gt;
    Guarantees shortest path in terms of number of edges (unweighted graphs).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Cons:&lt;/strong&gt;
    Uninformed, does not consider edge weights, explores level by level, can be slow in large graphs for weighted paths.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;A* vs. BFS:&lt;/strong&gt;
    A* with a good heuristic is typically much faster for weighted graphs and can be faster for unweighted graphs too by intelligently pruning the search.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Greedy Best-First Search:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pros:&lt;/strong&gt;
    Very fast, explores only based on &lt;code&gt;h(n)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Cons:&lt;/strong&gt;
    Does not guarantee optimal path; can get stuck in local minima or take suboptimal long paths if &lt;code&gt;h(n)&lt;/code&gt; is misleading.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;A* vs. Greedy Best-First:&lt;/strong&gt;
    A* balances &lt;code&gt;g(n)&lt;/code&gt; and &lt;code&gt;h(n)&lt;/code&gt;, guaranteeing optimality while still benefiting from heuristic guidance. Greedy Best-First only uses &lt;code&gt;h(n)&lt;/code&gt;, sacrificing optimality for speed.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaway for Understanding A* Search:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A* strikes an excellent balance between speed and optimality. Its performance is heavily reliant on the quality of its heuristic function. A well-designed, admissible, and consistent heuristic transforms A* into an incredibly efficient and powerful pathfinding tool for a vast array of problems, making it a cornerstone algorithm in AI and robotics.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="real-world-applications-of-a-search"&gt;Real-World Applications of A* Search&lt;/h2&gt;
&lt;p&gt;The versatility and efficiency of A* search make it an indispensable tool across a myriad of domains, extending far beyond academic curiosity into practical, mission-critical systems. Its ability to find optimal paths quickly has cemented its status as a go-to algorithm for intelligent navigation and planning.&lt;/p&gt;
&lt;h3 id="1-video-game-artificial-intelligence-ai"&gt;1. Video Game Artificial Intelligence (AI)&lt;/h3&gt;
&lt;p&gt;Perhaps the most common and visible application of A* is in video games. From classic strategy games to modern open-world environments, A* is the backbone of Non-Player Character (NPC) movement and decision-making.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;NPC Pathfinding:&lt;/strong&gt;
    AI-controlled characters often need to navigate complex maps, find enemies, avoid obstacles, or reach specific objectives. A* enables them to compute the shortest or safest route in real-time. For instance, in real-time strategy games like StarCraft or Age of Empires, units use A* to pathfind around terrain and other units.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Level Design and Analysis:&lt;/strong&gt;
    Game designers can use A* to test map layouts for reachability, ensuring that all parts of a level are accessible and that challenges are appropriately scaled based on path complexity.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Enemy AI:&lt;/strong&gt;
    Enemies might use A* to flank players, escape danger, or patrol areas efficiently. The heuristic can be adapted to represent different "costs," such as avoiding enemy sightlines or moving through cover.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-robotics-and-autonomous-navigation"&gt;2. Robotics and Autonomous Navigation&lt;/h3&gt;
&lt;p&gt;For robots to operate effectively in physical environments, they must be able to plan their movements. A* is a core algorithm for robot navigation and motion planning.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Autonomous Vehicles:&lt;/strong&gt;
    Self-driving cars employ variants of A* to plan routes through road networks, accounting for traffic, road conditions, and dynamic obstacles.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Robotic Explorers:&lt;/strong&gt;
    Robots exploring unknown terrains, such as Mars rovers or warehouse automation robots, use A* to plan paths from their current location to a target, avoiding known obstacles and adapting to newly discovered terrain features.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Industrial Automation:&lt;/strong&gt;
    Manufacturing robots use pathfinding for efficient assembly lines, navigating their workspaces without collisions and optimizing task execution order.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-logistics-and-transportation"&gt;3. Logistics and Transportation&lt;/h3&gt;
&lt;p&gt;Optimizing routes for delivery services, public transport, or supply chains is a massive logistical challenge, where A* plays a pivotal role.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;GPS Navigation Systems:&lt;/strong&gt;
    Modern GPS devices and mapping applications (like Google Maps or Waze) use sophisticated pathfinding algorithms, often building upon A* principles, to calculate the fastest or shortest routes, considering real-time traffic data, road closures, and user preferences.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Delivery Route Optimization:&lt;/strong&gt;
    Companies like Amazon, FedEx, or UPS use algorithms derived from A* to plan the most efficient delivery routes for their fleets, saving time, fuel, and reducing operational costs.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Airline Scheduling:&lt;/strong&gt;
    While more complex than basic A*, the underlying principles of finding optimal paths through a network of flights and airports can leverage A*-like mechanisms for crew scheduling or flight connection planning.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-network-routing"&gt;4. Network Routing&lt;/h3&gt;
&lt;p&gt;In telecommunications and computer networking, A* (or its variants) can be used to determine optimal data packet paths.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Shortest Path Routing:&lt;/strong&gt;
    In certain network architectures, A* can help identify the most efficient route for data packets to travel from a source to a destination, minimizing latency or maximizing throughput.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Traffic Engineering:&lt;/strong&gt;
    Beyond simple shortest paths, A* can be adapted to consider network congestion, link capacities, and quality-of-service requirements to route traffic effectively.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-artificial-intelligence-planning"&gt;5. Artificial Intelligence Planning&lt;/h3&gt;
&lt;p&gt;In broader AI contexts, A* is used for planning problems where an agent needs to sequence actions to achieve a goal.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Problem Solving:&lt;/strong&gt;
    A* can find the shortest sequence of actions to transform an initial state into a goal state. Examples include solving puzzles like the 8-puzzle or Rubik's Cube.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Automated Reasoning:&lt;/strong&gt;
    In knowledge-based systems, A* can explore possible inference paths to prove a theorem or answer a query.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The extensive adoption of A* search across these diverse fields underscores its practical utility. Its robustness, combined with its ability to adapt to various cost functions and heuristics, makes it a powerful algorithm for solving real-world pathfinding and planning challenges.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="advantages-and-limitations-of-a-search"&gt;Advantages and Limitations of A* Search&lt;/h2&gt;
&lt;p&gt;Like any powerful tool, A* search comes with a set of distinct advantages that make it a preferred choice in many scenarios, alongside inherent limitations that dictate its suitability for particular problems. Understanding these aspects is crucial for effectively deploying the algorithm.&lt;/p&gt;
&lt;h3 id="advantages-of-a-search"&gt;Advantages of A* Search&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Optimality:&lt;/strong&gt;
    Provided the heuristic function &lt;code&gt;h(n)&lt;/code&gt; is admissible (never overestimates the actual cost to the goal) and edge weights are non-negative, A* is guaranteed to find the shortest path from the start node to the goal node. This guarantee is a significant differentiator from purely greedy search algorithms.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Completeness:&lt;/strong&gt;
    If a path to the goal exists in the graph, A* is guaranteed to find it. It will not miss a solution if one is present, assuming finite graph traversal is possible.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Efficiency (with good heuristic):&lt;/strong&gt;
    By intelligently guiding its search using the &lt;code&gt;h(n)&lt;/code&gt; heuristic, A* explores far fewer nodes than uninformed search algorithms like Dijkstra's or BFS in many practical applications. This results in significantly faster path discovery, especially in large search spaces.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Flexibility:&lt;/strong&gt;
    The algorithm can be adapted to various problem types simply by changing the graph representation, cost function (&lt;code&gt;g(n)&lt;/code&gt;), and heuristic function (&lt;code&gt;h(n)&lt;/code&gt;). This adaptability makes it suitable for diverse applications, from game AI to logistics.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Targeted Search:&lt;/strong&gt;
    A* focuses its search towards the goal, expanding nodes that appear to be on the most promising path. This goal-directed approach minimizes wasted computation.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="limitations-of-a-search"&gt;Limitations of A* Search&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt;
    This is often the most significant drawback of A*. In the worst case, A* needs to store all expanded (closed list) and frontier (open list) nodes in memory. For extremely large search spaces or graphs, this &lt;code&gt;O(V)&lt;/code&gt; space requirement can quickly exhaust available memory, making the algorithm impractical.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Heuristic Dependency:&lt;/strong&gt;
    The performance of A* is highly dependent on the quality of its heuristic.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Poor Heuristic:&lt;/strong&gt;
    A weak heuristic (one that poorly estimates the remaining cost) can make A* behave more like Dijkstra's, exploring many unnecessary nodes.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Inadmissible Heuristic:&lt;/strong&gt;
    An inadmissible heuristic (one that overestimates the cost) might lead A* to find a path faster but offers no guarantee of optimality, potentially returning a suboptimal path.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Heuristic Design:&lt;/strong&gt;
    Designing a good, admissible, and consistent heuristic can be challenging and domain-specific.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Static Environments:&lt;/strong&gt;
    A* is inherently designed for static or semi-static environments where the graph structure and edge weights do not change frequently. In highly dynamic environments, where obstacles appear or disappear rapidly, or costs fluctuate, the path computed by A* can quickly become outdated. Re-running A* frequently can be computationally expensive.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Overhead of Priority Queue:&lt;/strong&gt;
    While a priority queue (like a min-heap) is essential for efficiency, its operations (inserting, extracting min) have logarithmic time complexity (&lt;code&gt;O(log N)&lt;/code&gt;). For very dense graphs or frequent updates, this overhead can add up.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Not Always Optimal for All Metrics:&lt;/strong&gt;
    While it finds the shortest path in terms of &lt;code&gt;g(n)&lt;/code&gt; (the accumulated cost), it might not find the path with the fewest turns, or the smoothest path, unless these metrics are explicitly incorporated into the &lt;code&gt;g(n)&lt;/code&gt; and &lt;code&gt;h(n)&lt;/code&gt; functions.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Despite its limitations, the strengths of A* often outweigh its weaknesses for a broad range of pathfinding problems. When memory is not a severe constraint and a good heuristic can be formulated, A* remains the algorithm of choice for optimal and efficient pathfinding. Researchers continue to develop variants and optimizations to mitigate its memory footprint and improve its adaptability to dynamic conditions.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="optimizations-and-variants-of-a-search"&gt;Optimizations and Variants of A* Search&lt;/h2&gt;
&lt;p&gt;While the base A* algorithm is powerful, its limitations, particularly regarding space complexity, have spurred the development of various optimizations and alternative approaches. These variants aim to tackle specific challenges, such as memory constraints or dynamic environments, while retaining A*'s core advantages.&lt;/p&gt;
&lt;h3 id="1-iterative-deepening-a-ida"&gt;1. Iterative Deepening A&lt;em&gt; (IDA&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Problem Addressed:&lt;/strong&gt;
    Primarily space complexity.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;How it Works:&lt;/strong&gt;
    IDA* performs a series of depth-first searches, each with an increasing &lt;code&gt;f(n)&lt;/code&gt; limit. It starts with an &lt;code&gt;f(n)&lt;/code&gt; limit equal to &lt;code&gt;h(start_node)&lt;/code&gt;. If the goal is not found within this limit, the limit is increased to the smallest &lt;code&gt;f(n)&lt;/code&gt; value of any node that exceeded the previous limit. This process repeats until the goal is found.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;
    Optimal and complete (like A*), but has &lt;code&gt;O(b^d)&lt;/code&gt; time complexity and &lt;code&gt;O(d)&lt;/code&gt; space complexity (where &lt;code&gt;d&lt;/code&gt; is path depth, &lt;code&gt;b&lt;/code&gt; is branching factor). This makes it ideal for problems where memory is extremely limited.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;
    It re-explores nodes multiple times, which can lead to higher time complexity than A* in some cases.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-memory-bounded-a-ma-sma"&gt;2. Memory-Bounded A&lt;em&gt; (MA&lt;/em&gt;, SMA*)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Problem Addressed:&lt;/strong&gt;
    Space complexity.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;How it Works:&lt;/strong&gt;
    These algorithms, like Simplified Memory-Bounded A* (SMA*), operate with a fixed memory limit. When the memory limit is reached, they discard the "worst" node (typically the node with the highest &lt;code&gt;f(n)&lt;/code&gt;) from memory, prioritizing nodes that seem most promising. If a discarded node is later found to be necessary, it's re-generated.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;
    Guarantees to find the optimal path given the memory constraint (if a path exists), and explores as much as possible within that constraint.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;
    Can be slower than A* due to re-generating discarded subtrees. Its optimality guarantee is conditional on having sufficient memory to store the optimal path's critical nodes.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-jump-point-search-jps"&gt;3. Jump Point Search (JPS)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Problem Addressed:&lt;/strong&gt;
    Time complexity for grid-based maps.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;How it Works:&lt;/strong&gt;
    JPS is a significant optimization for uniform cost grids (like game maps) where movement is restricted to cardinal and diagonal directions. It prunes redundant neighbors by identifying "jump points" – nodes that are either forced neighbors or have forced neighbors – thereby significantly reducing the number of nodes A* has to evaluate.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;
    Can be dramatically faster than A* on large, open grid maps, often by a factor of 10-20x, because it avoids redundant checks of "straight-line" neighbors.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;
    Primarily applicable to uniform-cost, grid-based maps. Not suitable for general graphs or varying edge weights. The heuristic still needs to be admissible and consistent (e.g., Euclidean or Chebyshev distance).&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-theta-and-any-angle-pathfinding"&gt;4. Theta* and Any-Angle Pathfinding&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Problem Addressed:&lt;/strong&gt;
    Realistic movement paths. Standard A* often generates paths that "stick to the grid," turning at nodes, which can look unnatural for continuous movement.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;How it Works:&lt;/strong&gt;
    Theta* modifies A* to consider "any-angle" paths, allowing agents to move directly between any visible nodes, rather than being restricted to grid edges. It does this by checking line-of-sight between current node and ancestors, potentially "cutting corners."&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;
    Produces shorter, more realistic, and smoother paths in continuous space representations (like navigation meshes or continuous grids).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;
    More complex to implement than standard A*. Visibility checks can be computationally intensive, though optimized implementations exist.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-hierarchical-a-hna"&gt;5. Hierarchical A&lt;em&gt; (HNA&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Problem Addressed:&lt;/strong&gt;
    Scaling to very large maps.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;How it Works:&lt;/strong&gt;
    Divides a large map into smaller regions or layers. A high-level search plans a path between regions, and then a low-level search plans the path within each chosen region.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;
    Dramatically reduces the search space for very large maps, leading to faster computations. Useful for game levels with distinct zones or large outdoor environments.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;
    Can sometimes find suboptimal paths because the hierarchy might force a path through a "chokepoint" even if a slightly longer but more direct path exists outside the high-level representation.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These variants demonstrate the ongoing effort to refine and adapt A* search to meet the evolving demands of complex computational problems, ensuring its continued relevance in the tech landscape.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="the-future-outlook-of-pathfinding-and-a"&gt;The Future Outlook of Pathfinding and A*&lt;/h2&gt;
&lt;p&gt;The realm of pathfinding, spearheaded by algorithms like A*, is far from static. As computational power grows, data availability increases, and our understanding of complex systems deepens, the future of pathfinding promises exciting advancements.&lt;/p&gt;
&lt;h3 id="integration-with-machine-learning"&gt;Integration with Machine Learning&lt;/h3&gt;
&lt;p&gt;One of the most promising frontiers is the synergy between classical pathfinding algorithms and machine learning.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Learned Heuristics:&lt;/strong&gt;
    Instead of hand-crafting heuristics, machine learning models could learn optimal or near-optimal heuristic functions from vast datasets of successful pathfinding examples. This could lead to highly adaptive and context-aware heuristics that outperform static ones.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Dynamic Environments:&lt;/strong&gt;
    &lt;a href="https://analyticsdrive.tech/reinforcement-learning/"&gt;Reinforcement Learning&lt;/a&gt; (RL) agents could learn to navigate dynamic environments where traditional A* struggles. RL could teach agents how to react to real-time changes in the environment (e.g., moving obstacles, changing road conditions) by choosing actions that align with optimal pathfinding principles.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Predictive Pathfinding:&lt;/strong&gt;
    ML could predict future states of the environment (e.g., traffic patterns, enemy movements) and feed these predictions into A* or its variants to enable more proactive and adaptive path planning.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="pathfinding-in-multi-agent-systems"&gt;Pathfinding in Multi-Agent Systems&lt;/h3&gt;
&lt;p&gt;The complexity escalates when multiple agents need to find paths simultaneously while avoiding collisions with each other.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Cooperative Pathfinding:&lt;/strong&gt;
    Algorithms like Conflict-Based Search (CBS) or its derivatives are emerging to handle multi-agent pathfinding (MAPF) by iteratively solving individual A* problems and resolving conflicts. Future research will focus on scaling these solutions to thousands or even millions of agents.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Decentralized Systems:&lt;/strong&gt;
    Developing decentralized pathfinding solutions where agents can plan locally and cooperate globally will be crucial for massive simulations, autonomous drone swarms, or smart city traffic management.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="quantum-computings-potential"&gt;Quantum Computing's Potential&lt;/h3&gt;
&lt;p&gt;While still in its nascent stages, quantum computing holds speculative but potentially transformative implications for pathfinding.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Faster Search:&lt;/strong&gt;
    Quantum algorithms, such as Grover's algorithm, could theoretically speed up unstructured search problems. If applied to parts of the pathfinding process, it might offer exponential speedups in specific scenarios, though translating classical graph problems to quantum architectures is a significant challenge.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Complex Optimizations:&lt;/strong&gt;
    Quantum annealing could potentially tackle highly complex, multi-objective pathfinding problems where current classical algorithms struggle to find optimal solutions in reasonable timeframes.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="human-ai-collaboration-in-pathfinding"&gt;Human-AI Collaboration in Pathfinding&lt;/h3&gt;
&lt;p&gt;The future might also see more intuitive interfaces where humans guide or refine AI-generated paths. Imagine a drone operator providing high-level goals, and the drone's A* algorithm filling in the detailed, collision-free trajectory, with the ability for human intervention and adjustment. This blend of algorithmic efficiency and human intuition could lead to more robust and trustworthy autonomous systems.&lt;/p&gt;
&lt;p&gt;A* search, with its elegant balance of informed guidance and guaranteed optimality, will undoubtedly remain a foundational algorithm. However, its evolution will increasingly involve hybrid approaches, integrating with emerging technologies like machine learning and exploring new computational paradigms to meet the ever-growing demands for intelligent and adaptive navigation solutions.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the main difference between A* and Dijkstra's algorithm?&lt;/strong&gt;
A: A* is an informed search algorithm that uses a heuristic to estimate the cost to the goal, guiding its search more efficiently than Dijkstra's. Dijkstra's is an uninformed search, exploring all directions without a heuristic.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What makes a good heuristic function for A*?&lt;/strong&gt;
A: A good heuristic is admissible, meaning it never overestimates the actual cost to the goal. It should also be as accurate as possible without overestimation to guide the search effectively and reduce the number of nodes explored.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: In what real-world scenarios is A* search commonly used?&lt;/strong&gt;
A: A* is widely used in video game AI for NPC pathfinding, robotics for autonomous navigation, GPS and logistics for route optimization, and general artificial intelligence planning problems.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/A*_search_algorithm"&gt;A* Search Algorithm Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.redblobgames.com/pathfinding/a-star/introduction.html"&gt;Introduction to A* Search (Amit Patel's Red Blob Games)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://theory.stanford.edu/~amitp/GameProgramming/AStarComparison.html"&gt;Pathfinding with A* (Stanford University)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://aima.cs.berkeley.edu/"&gt;Artificial Intelligence: A Modern Approach (Book by Stuart Russell and Peter Norvig)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Graph Theory"/><category term="Competitive Programming"/><category term="Artificial Intelligence"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/understanding-a-star-search-pathfinding-algorithm-tutorial.webp" width="1200"/><media:title type="plain">Understanding A* Search: Pathfinding Algorithm Tutorial</media:title><media:description type="plain">Explore Understanding A* Search, a critical pathfinding algorithm. Learn its mechanics, key components, and real-world applications in AI, robotics, and gaming.</media:description></entry><entry><title>What is a Hash Map? Deep Dive into Hashing Concepts Unveiled</title><link href="https://analyticsdrive.tech/what-is-a-hash-map-hashing-concepts/" rel="alternate"/><published>2026-03-22T21:42:00+05:30</published><updated>2026-03-22T21:42:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-22:/what-is-a-hash-map-hashing-concepts/</id><summary type="html">&lt;p&gt;A comprehensive guide on what is a Hash Map, exploring its inner workings, hashing concepts, collision resolution, and real-world applications.&lt;/p&gt;</summary><content type="html">&lt;p&gt;In the fast-paced world of software development and data management, efficiency is paramount. When it comes to storing and retrieving data quickly, few data structures are as powerful and ubiquitous as the hash map. But &lt;strong&gt;what is a Hash Map? Deep Dive into Hashing Concepts&lt;/strong&gt; reveals that it's far more than just a simple container; it's an elegant solution built upon ingenious mathematical principles to achieve near-instantaneous data access. Understanding its mechanics, from the core idea of mapping keys to values to the intricate strategies for handling potential conflicts, is fundamental for any tech-savvy professional looking to optimize their applications. This comprehensive guide will unveil the inner workings of this indispensable data structure, providing a deep dive into its architecture, performance characteristics, and widespread applications.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#understanding-the-core-what-is-a-hash-map-deep-dive-into-its-essence"&gt;Understanding the Core: What is a Hash Map? Deep Dive into Its Essence&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-analogy-of-a-super-efficient-library"&gt;The Analogy of a Super-Efficient Library&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#formal-definition-and-key-characteristics"&gt;Formal Definition and Key Characteristics&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-inner-workings-how-hashing-concepts-drive-efficiency"&gt;The Inner Workings: How Hashing Concepts Drive Efficiency&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-role-of-the-hash-function"&gt;The Role of the Hash Function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-challenge-of-collisions"&gt;The Challenge of Collisions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#collision-resolution-strategies"&gt;Collision Resolution Strategies&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#chaining-separate-chaining"&gt;Chaining (Separate Chaining)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#open-addressing"&gt;Open Addressing&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#linear-probing"&gt;Linear Probing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#quadratic-probing"&gt;Quadratic Probing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#double-hashing"&gt;Double Hashing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#key-performance-metrics-and-optimizations"&gt;Key Performance Metrics and Optimizations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#load-factor-the-balancing-act"&gt;Load Factor: The Balancing Act&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#resizing-and-rehashing"&gt;Resizing and Rehashing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-implementations-across-programming-languages"&gt;Common Implementations Across Programming Languages&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#python-dictionaries-dict"&gt;Python Dictionaries (dict)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#java-hashmap"&gt;Java HashMap&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#c-stdunordered_map"&gt;C++ std::unordered_map&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-hash-maps"&gt;Real-World Applications of Hash Maps&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#advantages-and-disadvantages-of-hash-maps"&gt;Advantages and Disadvantages of Hash Maps&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#advantages"&gt;Advantages:&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#disadvantages"&gt;Disadvantages:&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#advanced-hashing-concepts-and-future-trends"&gt;Advanced Hashing Concepts and Future Trends&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#perfect-hashing"&gt;Perfect Hashing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#cuckoo-hashing"&gt;Cuckoo Hashing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#extendible-hashing"&gt;Extendible Hashing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#trends-in-hashing-research"&gt;Trends in Hashing Research&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion-mastering-the-mighty-hash-map"&gt;Conclusion: Mastering the Mighty Hash Map&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="understanding-the-core-what-is-a-hash-map-deep-dive-into-its-essence"&gt;Understanding the Core: What is a Hash Map? Deep Dive into Its Essence&lt;/h2&gt;
&lt;p&gt;At its heart, a hash map (also known as a hash table, dictionary, or associative array) is a data structure that implements an associative array abstract data type. It stores collections of key-value pairs, where each key is unique and maps to a specific value. Think of it like a highly organized filing cabinet or a dictionary where you can look up the definition (value) directly by knowing the word (key), without having to scan through every single page. This direct access is what gives hash maps their incredible speed. To truly appreciate this efficiency, it's beneficial to understand how performance is measured using concepts like &lt;a href="/big-o-notation-explained-beginner-guide-complexity/"&gt;Big O Notation Explained: A Beginner's Guide to Complexity&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id="the-analogy-of-a-super-efficient-library"&gt;The Analogy of a Super-Efficient Library&lt;/h3&gt;
&lt;p&gt;Imagine a library with millions of books. If you wanted to find a specific book, say "The Hitchhiker's Guide to the Galaxy," and it was just placed randomly on shelves, finding it would be a nightmare. You'd have to check every single book until you stumbled upon it – a process that could take an incredibly long time, proportional to the number of books in the library (O(N) time complexity).&lt;/p&gt;
&lt;p&gt;Now, imagine this library uses a system: each book's title is "processed" by a special librarian (the &lt;em&gt;hash function&lt;/em&gt;) who generates a unique shelf number (the &lt;em&gt;index&lt;/em&gt; or &lt;em&gt;hash value&lt;/em&gt;) for that book. When you want to retrieve "The Hitchhiker's Guide," you just tell the librarian the title, they quickly calculate its shelf number, and you go directly to that shelf. If there are multiple books on that same shelf, you only need to check a few, not the entire library. This direct, almost instant access is the magic of a hash map, allowing you to find your book in roughly constant time (O(1) on average). This efficient system is precisely why &lt;strong&gt;what is a Hash Map? Deep Dive into Hashing Concepts&lt;/strong&gt; is such a critical topic.&lt;/p&gt;
&lt;h3 id="formal-definition-and-key-characteristics"&gt;Formal Definition and Key Characteristics&lt;/h3&gt;
&lt;p&gt;A hash map essentially consists of an array (often called a bucket array or hash table) where data is stored. Each position in this array is called a "bucket." When you want to store a key-value pair, the key is passed through a special function called a &lt;em&gt;hash function&lt;/em&gt;. This function computes an integer, the hash value, which is then typically mapped to an index within the bucket array.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Key-Value Pairs:&lt;/strong&gt; Stores data as unique keys mapped to associated values.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unordered:&lt;/strong&gt; Unlike arrays or linked lists, the elements in a hash map are not stored in any particular order based on their keys or values. The order is determined by the hash function.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Average O(1) Time Complexity:&lt;/strong&gt; The most significant advantage is its average-case time complexity for insertion, deletion, and retrieval operations, which is constant. This means the time taken for these operations generally doesn't increase with the number of elements stored.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reliance on Hash Function:&lt;/strong&gt; The performance and efficiency of a hash map heavily depend on the quality of its hash function.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="the-inner-workings-how-hashing-concepts-drive-efficiency"&gt;The Inner Workings: How Hashing Concepts Drive Efficiency&lt;/h2&gt;
&lt;p&gt;The efficiency of a hash map hinges on its ability to quickly convert a key into an array index. This conversion is handled by a crucial component: the hash function. However, perfect conversion is rarely possible, leading to situations known as "collisions," which require robust resolution strategies.&lt;/p&gt;
&lt;h3 id="the-role-of-the-hash-function"&gt;The Role of the Hash Function&lt;/h3&gt;
&lt;p&gt;A hash function is an algorithm that takes an input (the key) and returns a fixed-size integer, which serves as an index in the array of buckets. For a hash map, the primary goal of the hash function is to distribute keys as evenly as possible across the entire range of potential indices.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Properties of a Good Hash Function:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Deterministic:&lt;/strong&gt; Given the same input key, it must always produce the same hash value. This ensures that when you try to retrieve a value, the hash function leads you back to the correct location.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fast Computation:&lt;/strong&gt; The function itself should be computationally inexpensive. If calculating the hash takes a long time, it negates the speed benefits of the hash map.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Uniform Distribution:&lt;/strong&gt; This is perhaps the most critical property. A good hash function should distribute keys uniformly across the available buckets. This minimizes collisions and keeps the average time complexity close to O(1). A poor distribution can lead to "clustering," where many keys map to the same few buckets, degrading performance to O(N) in the worst case.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Minimizes Collisions:&lt;/strong&gt; While perfect collision avoidance is often impossible, a good hash function strives to keep collisions to a minimum.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Example: Simple Hash Functions&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Integer Keys:&lt;/strong&gt; For integer keys, a common simple hash function is the modulo operator: &lt;code&gt;hash_value = key % table_size&lt;/code&gt;. This maps any integer key to an index within the &lt;code&gt;[0, table_size-1]&lt;/code&gt; range.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;String Keys:&lt;/strong&gt; Hashing strings is more complex. A common approach involves summing the ASCII values of characters, often weighted by their position or powers of a prime number, and then applying a modulo operation. For instance, &lt;code&gt;hash(s) = (s[0]*P^(L-1) + s[1]*P^(L-2) + ... + s[L-1]*P^0) % table_size&lt;/code&gt;, where P is a prime number and L is the length of the string.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="the-challenge-of-collisions"&gt;The Challenge of Collisions&lt;/h3&gt;
&lt;p&gt;A collision occurs when two different keys, when passed through the hash function, produce the same hash value (and thus map to the same bucket index). Because the hash table has a finite number of buckets, while the set of possible keys can be infinite, collisions are inevitable. They are a fundamental aspect of hashing and not a flaw.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Impact on Performance:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;When collisions occur, the hash map cannot immediately determine which key-value pair to retrieve or store by just looking at the index. It needs an additional mechanism to handle these multiple items at the same bucket. If collisions are too frequent or not handled efficiently, the average O(1) performance can degrade, potentially approaching O(N), much like searching an unsorted list. Effective collision resolution is therefore paramount to maintaining a hash map's speed.&lt;/p&gt;
&lt;h3 id="collision-resolution-strategies"&gt;Collision Resolution Strategies&lt;/h3&gt;
&lt;p&gt;Addressing collisions efficiently is vital for the performance of a hash map. There are two primary categories of strategies: Chaining and Open Addressing.&lt;/p&gt;
&lt;h4 id="chaining-separate-chaining"&gt;Chaining (Separate Chaining)&lt;/h4&gt;
&lt;p&gt;Chaining is one of the most common and straightforward collision resolution techniques.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;How it works:&lt;/strong&gt; Instead of storing the key-value pair directly in the bucket array, each bucket in the array holds a reference to a dynamic data structure, typically a linked list or a dynamic array (like Python's list or Java's &lt;code&gt;ArrayList&lt;/code&gt;). When a collision occurs, the new key-value pair is simply appended to the list at the calculated hash index. For a deeper understanding of such structures, refer to our guide on &lt;a href="/linked-lists-python-deep-dive-tutorial-data-structures/"&gt;Linked Lists in Python: A Deep Dive Tutorial into Data Structures&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visualizing Chaining:&lt;/strong&gt; Imagine each slot in your library's shelf (the bucket) is actually a mini-shelf that can hold multiple books. If two books hash to shelf #5, they both get placed on mini-shelf #5. When you look for a book on shelf #5, you then just linearly search through the few books on that mini-shelf.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Pros of Chaining:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Simplicity:&lt;/strong&gt; Relatively easy to implement.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No Clustering:&lt;/strong&gt; It effectively avoids the "primary clustering" problem seen in some open addressing schemes, where long sequences of occupied slots form.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unlimited Elements:&lt;/strong&gt; The number of elements that can be stored is not strictly limited by the table size, as linked lists can grow indefinitely.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Less Sensitive to Load Factor:&lt;/strong&gt; It can tolerate higher load factors (more items than buckets) more gracefully than open addressing, though performance will degrade.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Cons of Chaining:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Memory Overhead:&lt;/strong&gt; Requires extra memory for pointers (in linked lists) or managing dynamic arrays.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cache Performance:&lt;/strong&gt; Traversing linked lists can lead to poorer cache performance due to non-contiguous memory access.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Secondary Search:&lt;/strong&gt; While the hash function gives direct access to the bucket, a secondary linear search is still required within the linked list at that bucket, which can become slow if the lists are long.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="open-addressing"&gt;Open Addressing&lt;/h4&gt;
&lt;p&gt;Open addressing is an alternative where, if a collision occurs, the system "probes" (searches) for another empty slot in the hash table itself, rather than creating an external data structure. The table size must always be greater than or equal to the number of elements.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;How it works:&lt;/strong&gt; When trying to insert a key-value pair, if the calculated hash index is already occupied, a probe sequence is used to find the next available slot. When searching for a key, the same probe sequence is followed until the key is found or an empty slot is encountered (indicating the key is not present).&lt;/li&gt;
&lt;/ul&gt;
&lt;h5 id="linear-probing"&gt;Linear Probing&lt;/h5&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; If index &lt;code&gt;h(key)&lt;/code&gt; is occupied, try &lt;code&gt;(h(key) + 1) % table_size&lt;/code&gt;, then &lt;code&gt;(h(key) + 2) % table_size&lt;/code&gt;, and so on. It linearly searches for the next available slot.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Challenge: Primary Clustering:&lt;/strong&gt; The main drawback is primary clustering. Long runs of occupied slots start to form, increasing the average search time. Any new key that hashes into a cluster will have to linearly probe through the entire cluster to find an empty spot, further extending the cluster.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Example:&lt;/strong&gt; If slots 5, 6, 7 are occupied, and a new key hashes to 5, it will try 6, then 7, then 8. If 8 is also occupied, it will go to 9, creating an even longer cluster.&lt;/li&gt;
&lt;/ul&gt;
&lt;h5 id="quadratic-probing"&gt;Quadratic Probing&lt;/h5&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; To mitigate primary clustering, quadratic probing uses a quadratic sequence: &lt;code&gt;(h(key) + 1^2) % table_size&lt;/code&gt;, then &lt;code&gt;(h(key) + 2^2) % table_size&lt;/code&gt;, &lt;code&gt;(h(key) + 3^2) % table_size&lt;/code&gt;, etc. This spreads out probes more effectively.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Challenge: Secondary Clustering:&lt;/strong&gt; While it avoids primary clustering, it can suffer from secondary clustering. If two distinct keys hash to the &lt;em&gt;same initial index&lt;/em&gt;, they will follow the &lt;em&gt;exact same probe sequence&lt;/em&gt;, leading to conflicts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Probe Sequence:&lt;/strong&gt; &lt;code&gt;(h(key) + c1*i + c2*i^2) % table_size&lt;/code&gt; for &lt;code&gt;i = 0, 1, 2, ...&lt;/code&gt; where &lt;code&gt;c1&lt;/code&gt; and &lt;code&gt;c2&lt;/code&gt; are constants.&lt;/li&gt;
&lt;/ul&gt;
&lt;h5 id="double-hashing"&gt;Double Hashing&lt;/h5&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; Double hashing uses a second hash function &lt;code&gt;h2(key)&lt;/code&gt; to determine the step size for probing. If &lt;code&gt;h(key)&lt;/code&gt; is occupied, the next probes are &lt;code&gt;(h(key) + 1*h2(key)) % table_size&lt;/code&gt;, then &lt;code&gt;(h(key) + 2*h2(key)) % table_size&lt;/code&gt;, &lt;code&gt;(h(key) + 3*h2(key)) % table_size&lt;/code&gt;, and so on. The second hash function must never return zero to ensure all slots can be probed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Advantage:&lt;/strong&gt; This method is excellent at reducing both primary and secondary clustering because each key that hashes to the same initial index &lt;code&gt;h(key)&lt;/code&gt; will still have a unique probe sequence determined by &lt;code&gt;h2(key)&lt;/code&gt;. This offers the best distribution among open addressing schemes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Constraint:&lt;/strong&gt; The &lt;code&gt;h2(key)&lt;/code&gt; function must produce a value relatively prime to the &lt;code&gt;table_size&lt;/code&gt; to ensure all slots are eventually visited.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Pros of Open Addressing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Better Cache Performance:&lt;/strong&gt; Data is stored contiguously in memory, leading to better cache utilization compared to linked lists in chaining.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Less Memory Overhead:&lt;/strong&gt; No pointers needed for linked lists, potentially saving memory for individual entries.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Cons of Open Addressing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Sensitive to Load Factor:&lt;/strong&gt; Performance degrades drastically at high load factors (e.g., above 0.7 or 0.8), often requiring frequent resizing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deletion Complexity:&lt;/strong&gt; Deleting items can be tricky. Simply removing an item might break the probe chain for other items, making them unreachable. This often requires marking slots as "deleted" rather than truly empty, adding complexity.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Clustering:&lt;/strong&gt; While double hashing mitigates it significantly, clustering remains a potential issue for linear and quadratic probing.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="key-performance-metrics-and-optimizations"&gt;Key Performance Metrics and Optimizations&lt;/h2&gt;
&lt;p&gt;Understanding how to measure and optimize a hash map's performance is crucial for maximizing its utility. Two key concepts stand out: load factor and resizing.&lt;/p&gt;
&lt;h3 id="load-factor-the-balancing-act"&gt;Load Factor: The Balancing Act&lt;/h3&gt;
&lt;p&gt;The load factor (often denoted as &lt;script type="math/tex"&gt;\alpha&lt;/script&gt;) is a critical metric for hash map performance. It is defined as:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;Load Factor (α) = Number of Entries / Number of Buckets
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Impact on Performance:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Low Load Factor (α &amp;lt;&amp;lt; 1):&lt;/strong&gt; Means many empty buckets. Fewer collisions, faster lookups. However, it wastes memory.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;High Load Factor (α &amp;gt;&amp;gt; 1, especially &amp;gt; 1 for open addressing):&lt;/strong&gt; Means buckets are heavily loaded or full. Many collisions, slower lookups (linked lists grow long, probe sequences become extensive). For open addressing, a load factor greater than 1 is impossible because it means more elements than available slots.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Optimal Ranges:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Chaining:&lt;/strong&gt; Typically performs well with load factors between 0.7 and 1.0, though it can tolerate higher. As &lt;script type="math/tex"&gt;\alpha&lt;/script&gt; increases, the average length of linked lists grows proportionally, making operations &lt;script type="math/tex"&gt;O(1 + \alpha)&lt;/script&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Open Addressing:&lt;/strong&gt; Generally requires a load factor below 0.5 or 0.7 to maintain good performance. As &lt;script type="math/tex"&gt;\alpha&lt;/script&gt; approaches 1, the number of probes needed to find an empty slot (or an element) skyrockets.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;The Balancing Act:&lt;/strong&gt; The load factor represents a trade-off between space efficiency and time efficiency. A lower load factor offers faster access times but consumes more memory. A higher load factor saves memory but risks performance degradation. Developers must choose an appropriate threshold based on their application's needs.&lt;/p&gt;
&lt;h3 id="resizing-and-rehashing"&gt;Resizing and Rehashing&lt;/h3&gt;
&lt;p&gt;To maintain optimal performance as elements are added to a hash map, it often needs to resize its underlying array of buckets. This process is called rehashing.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why it's Needed:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;When the load factor exceeds a predefined threshold (e.g., 0.7 for Java's &lt;code&gt;HashMap&lt;/code&gt; or Python's dict), the probability of collisions increases significantly, and performance begins to degrade. To counter this, the hash map grows its capacity.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;The Process:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Create a New Array:&lt;/strong&gt; A new, larger array of buckets is allocated (typically double the size of the old array).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Re-hash All Elements:&lt;/strong&gt; Crucially, simply copying elements is not enough. Every existing key-value pair from the old hash map must be re-inserted into the &lt;em&gt;new&lt;/em&gt;, larger array. This is because the modulo operation (&lt;code&gt;% table_size&lt;/code&gt;) will produce different indices for most keys due to the changed &lt;code&gt;table_size&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Discard Old Array:&lt;/strong&gt; Once all elements are re-hashed into the new array, the old, smaller array is deallocated.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Amortized O(1) Complexity:&lt;/strong&gt; Rehashing is an expensive operation, taking &lt;script type="math/tex"&gt;O(N)&lt;/script&gt; time, where &lt;script type="math/tex"&gt;N&lt;/script&gt; is the number of elements in the map. However, because it doesn't happen very often (only when the load factor threshold is crossed), the average cost of an insertion operation over many insertions is still considered O(1) in an amortized sense. This means the infrequent expensive operations are "averaged out" by many cheap O(1) operations.&lt;/p&gt;
&lt;h2 id="common-implementations-across-programming-languages"&gt;Common Implementations Across Programming Languages&lt;/h2&gt;
&lt;p&gt;Hash maps are fundamental, and virtually every modern programming language provides an optimized implementation. While the core concepts remain the same, subtle differences exist in their default behaviors, hash functions, and collision resolution strategies.&lt;/p&gt;
&lt;h3 id="python-dictionaries-dict"&gt;Python Dictionaries (&lt;code&gt;dict&lt;/code&gt;)&lt;/h3&gt;
&lt;p&gt;Python's &lt;code&gt;dict&lt;/code&gt; is a highly optimized hash map implementation, renowned for its efficiency and ease of use.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Collision Resolution:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Uses open addressing, specifically a sophisticated variant of quadratic probing with some additional optimizations, including randomization to reduce the impact of bad hash functions. Python 3.6+ also introduced an ordered dictionary implementation detail (insertion order preservation) but it's still fundamentally a hash map.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Load Factor &amp;amp; Resizing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Automatically resizes when the load factor reaches a certain threshold.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Hash Function:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Python's built-in &lt;code&gt;hash()&lt;/code&gt; function is used for immutable objects (like integers, strings, tuples). Mutable objects (like lists, dictionaries, sets) cannot be used as keys because their hash value could change, making them unreachable.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Performance:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Offers excellent average-case O(1) performance for &lt;code&gt;insert&lt;/code&gt;, &lt;code&gt;delete&lt;/code&gt;, and &lt;code&gt;lookup&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="java-hashmap"&gt;Java &lt;code&gt;HashMap&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Java's &lt;code&gt;HashMap&lt;/code&gt; class is a widely used implementation of the &lt;code&gt;Map&lt;/code&gt; interface.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Collision Resolution:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Historically used chaining (linked lists at each bucket). Since Java 8, if a bucket's linked list becomes too long (typically &amp;gt; 8 nodes), it converts that linked list into a self-balancing &lt;a href="https://analyticsdrive.tech/binary-search-tree/"&gt;binary search tree&lt;/a&gt; (a red-black tree) to improve worst-case lookup time within that bucket from O(N) to O(log N).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Load Factor &amp;amp; Resizing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Defaults to a load factor of 0.75 and an initial capacity of 16. It resizes (doubles capacity) when the load factor is exceeded.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Hash Function:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Relies on the &lt;code&gt;hashCode()&lt;/code&gt; method provided by objects (and &lt;code&gt;equals()&lt;/code&gt; for key comparison). Developers are responsible for implementing these correctly for custom objects.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Performance:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Average O(1) for basic operations. Worst-case O(log N) for internal bucket searches in newer Java versions, mitigating the O(N) worst-case of simple chaining.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="c-stdunordered_map"&gt;C++ &lt;code&gt;std::unordered_map&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Introduced in C++11, &lt;code&gt;std::unordered_map&lt;/code&gt; provides a hash table implementation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Collision Resolution:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Implementation-dependent, but typically uses chaining.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Load Factor &amp;amp; Resizing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Allows users to control &lt;code&gt;max_load_factor()&lt;/code&gt; and &lt;code&gt;rehash()&lt;/code&gt; manually, though it also handles automatic resizing.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Hash Function:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Uses &lt;code&gt;std::hash&lt;/code&gt; for built-in types and provides mechanisms for users to define custom hash functions for their own classes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Performance:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Average O(1) performance for &lt;code&gt;insert&lt;/code&gt;, &lt;code&gt;erase&lt;/code&gt;, &lt;code&gt;find&lt;/code&gt;, and &lt;code&gt;operator[]&lt;/code&gt;. Worst-case is O(N) if many elements map to the same bucket.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="real-world-applications-of-hash-maps"&gt;Real-World Applications of Hash Maps&lt;/h2&gt;
&lt;p&gt;Hash maps are pervasive in modern computing. Their ability to provide rapid data access makes them indispensable for a wide array of applications, from fundamental system operations to complex data processing tasks.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Database Indexing:&lt;/strong&gt; Databases extensively use hash maps to index columns, enabling lightning-fast retrieval of records based on key values. When you query a database for a specific ID, a hash index can quickly point to the exact location of that record. Optimizing database performance often involves efficient indexing strategies, a topic explored further in &lt;a href="/how-to-optimize-sql-queries-peak-performance/"&gt;How to Optimize SQL Queries for Peak Performance&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Caching Systems:&lt;/strong&gt; Caches (e.g., web browser caches, CPU caches, distributed caches like Redis or Memcached) are essentially hash maps. They store frequently accessed data (key: URL/data ID, value: actual data) in memory for quick retrieval, avoiding expensive re-computation or disk I/O.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Symbol Tables in Compilers:&lt;/strong&gt; When a compiler processes source code, it uses a symbol table (a hash map) to store information about variables, functions, and classes (their names, types, scope, memory locations). This allows for rapid lookup and validation during compilation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unique Element Filtering and Sets:&lt;/strong&gt; Hash maps (or hash sets, which are hash maps where only keys are stored) are perfect for checking if an element exists in a collection or for finding unique elements. For instance, creating a &lt;code&gt;set&lt;/code&gt; from a list &lt;code&gt;[1, 2, 2, 3, 1]&lt;/code&gt; would efficiently produce &lt;code&gt;{1, 2, 3}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Counting Frequencies (Histograms):&lt;/strong&gt; To count the occurrences of words in a document or items in a list, a hash map is ideal. The word/item acts as the key, and its count as the value. &lt;code&gt;{"apple": 3, "banana": 1, "apple": 4}&lt;/code&gt; efficiently becomes &lt;code&gt;{"apple": 7, "banana": 1}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Network Routers:&lt;/strong&gt; Routers use hash tables to store routing tables, mapping IP addresses (keys) to outgoing network interfaces (values). This allows them to quickly determine where to forward incoming data packets.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Password Verification:&lt;/strong&gt; When you log into a system, your password isn't usually stored directly. Instead, a hash of your password is saved. When you enter your password, the system hashes it and compares the result with the stored hash. This isn't a hash map directly, but it leverages cryptographic hash functions, which share conceptual roots with the hash functions used in hash maps, in that they map an input to a fixed-size output.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Spell Checkers:&lt;/strong&gt; Hash maps can store dictionaries of correctly spelled words. When checking a word, the spell checker hashes it and quickly looks it up in the dictionary.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="advantages-and-disadvantages-of-hash-maps"&gt;Advantages and Disadvantages of Hash Maps&lt;/h2&gt;
&lt;p&gt;Like any data structure, hash maps come with their own set of strengths and weaknesses. Understanding these helps in making informed decisions about when and where to employ them.&lt;/p&gt;
&lt;h3 id="advantages"&gt;Advantages:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Exceptional Average-Case Time Complexity:&lt;/strong&gt; The most significant benefit is the average O(1) time complexity for insertion, deletion, and retrieval operations. This makes hash maps incredibly fast for dynamic data manipulation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Flexibility with Key Types:&lt;/strong&gt; Hash maps can use a wide variety of data types as keys (strings, objects, numbers), as long as a suitable hash function can be defined for them.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficient for Large Datasets:&lt;/strong&gt; As the number of elements grows, the performance remains consistently fast on average, making them suitable for managing vast amounts of data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ideal for Lookups:&lt;/strong&gt; If your primary operation is to quickly find if an item exists or retrieve its associated value, hash maps are often the best choice. This contrasts with structures like a &lt;a href="/binary-search-tree-step-by-step-implementation-guide/"&gt;Binary Search Tree: A Step-by-Step Implementation Guide for Developers&lt;/a&gt; which offers guaranteed logarithmic worst-case performance but at the cost of maintaining order.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="disadvantages"&gt;Disadvantages:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Worst-Case O(N) Time Complexity:&lt;/strong&gt; Despite the excellent average performance, a poorly designed hash function or an exceptionally high number of collisions can degrade the performance to O(N) for all operations. This can happen if all keys hash to the same bucket.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unordered Storage:&lt;/strong&gt; Hash maps do not maintain any inherent order of their elements. If you need ordered data (e.g., sorted by key), you would need to retrieve all elements and sort them separately, or use a different data structure like a balanced binary search tree (e.g., Java's &lt;code&gt;TreeMap&lt;/code&gt;, C++'s &lt;code&gt;std::map&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory Overhead:&lt;/strong&gt; For chaining, there is memory overhead due to the pointers in linked lists. For open addressing, resizing requires allocating a new, larger array and rehashing all elements, which can be memory-intensive and temporarily slow.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sensitivity to Hash Function Quality and Load Factor:&lt;/strong&gt; The efficiency of a hash map is highly dependent on the quality of its hash function and proper management of its load factor. A bad hash function leads to many collisions, and an improperly managed load factor triggers frequent or poorly timed rehashes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Difficult Deletion (Open Addressing):&lt;/strong&gt; In open addressing, simply deleting an element can create "holes" that break the probe sequences of other elements, making them unreachable. Special "tombstone" markers are often used, which complicate the logic and can degrade performance over time if not handled with periodic cleanup.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="advanced-hashing-concepts-and-future-trends"&gt;Advanced Hashing Concepts and Future Trends&lt;/h2&gt;
&lt;p&gt;The field of hashing is constantly evolving, with ongoing research focused on improving performance, security, and specialized applications. While basic hash maps are incredibly powerful, several advanced techniques address specific challenges.&lt;/p&gt;
&lt;h3 id="perfect-hashing"&gt;Perfect Hashing&lt;/h3&gt;
&lt;p&gt;Perfect hashing is a technique where a hash function is constructed such that there are &lt;em&gt;no collisions&lt;/em&gt; at all, assuming the set of keys is known in advance and remains static. This guarantees worst-case O(1) lookup time. It's often implemented using a two-level hashing scheme: a primary hash function maps keys to buckets, and each bucket then has its own secondary perfect hash function. This is typically used in scenarios with static dictionaries, like a compiler's symbol table for keywords.&lt;/p&gt;
&lt;h3 id="cuckoo-hashing"&gt;Cuckoo Hashing&lt;/h3&gt;
&lt;p&gt;Cuckoo hashing is an open-addressing scheme that uses &lt;em&gt;multiple hash functions&lt;/em&gt; (typically two). Each key can potentially reside in one of two possible locations (determined by the two hash functions). When inserting a key, if both locations are occupied, it "kicks out" an existing key from one of its potential locations, forcing that displaced key to find a new home using its other hash function, and so on. This "cuckoo" effect continues until an empty slot is found or a cycle is detected, requiring a rehash. Cuckoo hashing offers excellent average-case performance and a very strong guarantee of O(1) worst-case lookup time for successful searches.&lt;/p&gt;
&lt;h3 id="extendible-hashing"&gt;Extendible Hashing&lt;/h3&gt;
&lt;p&gt;Extendible hashing is a dynamic hashing technique particularly suitable for databases and file systems where data is stored on disk and the hash table might be too large to fit entirely in memory. It uses a directory of pointers to buckets. When a bucket overflows, only that bucket splits, and if necessary, the directory doubles in size. This minimizes the amount of data that needs to be rehashed and written to disk during resizing, making it efficient for large, disk-based data sets.&lt;/p&gt;
&lt;h3 id="trends-in-hashing-research"&gt;Trends in Hashing Research&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Concurrency:&lt;/strong&gt; Developing hash maps that perform efficiently in multi-threaded or distributed environments without heavy locking mechanisms. Concurrent hash maps (like Java's &lt;code&gt;ConcurrentHashMap&lt;/code&gt;) are a key area.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Security:&lt;/strong&gt; Cryptographic hash functions are crucial for data integrity and security, but even for non-cryptographic hash maps, resistance to "hash flooding attacks" (where malicious inputs cause many collisions, degrading performance to O(N)) is an ongoing concern.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hardware Acceleration:&lt;/strong&gt; Exploring how specialized hardware (e.g., FPGAs, ASICs) can accelerate hash function computation and collision resolution.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Adaptive Hashing:&lt;/strong&gt; Creating hash maps that can dynamically adjust their hash functions or collision resolution strategies based on observed data patterns and load, further optimizing performance in real-time.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="conclusion-mastering-the-mighty-hash-map"&gt;Conclusion: Mastering the Mighty Hash Map&lt;/h2&gt;
&lt;p&gt;The hash map stands as a testament to algorithmic ingenuity, providing an unparalleled solution for rapid data access in a myriad of computing scenarios. We've taken a deep dive into the fundamental &lt;strong&gt;hashing concepts&lt;/strong&gt; that empower this data structure, exploring the critical role of the hash function, the inevitable challenge of collisions, and the clever strategies like chaining and open addressing employed to resolve them. Understanding the nuances of load factor, the mechanics of resizing, and the typical implementations across popular programming languages reveals the sheer engineering elegance behind its average O(1) performance.&lt;/p&gt;
&lt;p&gt;From optimizing database lookups and powering caching systems to underpinning compiler operations and network routing, the hash map is an indispensable tool in the modern developer's arsenal. While it brings extraordinary speed, it also demands careful consideration of its potential drawbacks, such as worst-case performance scenarios and memory overhead. Mastering &lt;strong&gt;what is a Hash Map? Deep Dive into Hashing Concepts&lt;/strong&gt; not only equips you with a powerful data structure but also provides a deeper appreciation for the foundational algorithms that drive the digital world. As computing continues to evolve, the principles of efficient hashing will undoubtedly remain at the forefront of performance optimization.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the primary difference between a hash map and a regular array?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A hash map stores unordered key-value pairs, using a hash function to map keys to memory locations, providing average O(1) time for insertions, deletions, and lookups. A regular array stores ordered elements by integer index, offering O(1) access by index but typically O(N) for searching by value.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: When should I choose a hash map over other data structures like a binary search tree?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Choose a hash map when your primary need is extremely fast average-case O(1) lookups, insertions, and deletions based on a unique key, and the order of elements is not a concern. Opt for a binary search tree if you require elements to be stored in a sorted order, need efficient range queries, or demand a guaranteed O(log N) worst-case performance for all operations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What causes a hash map's performance to degrade?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A hash map's performance degrades primarily due to frequent collisions, which occur when multiple keys map to the same bucket. This can be caused by a poorly designed hash function that doesn't distribute keys evenly, or an excessively high load factor (too many items for too few buckets), leading to longer linked lists in chaining or extended probe sequences in open addressing, thus increasing time complexity towards O(N).&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Hash_table"&gt;Wikipedia: Hash Table&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/hashing-data-structure/"&gt;GeeksforGeeks: Hashing Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html"&gt;Oracle Java Documentation: HashMap&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries"&gt;Python Documentation: dict&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.cppreference.com/w/cpp/container/unordered_map"&gt;cppreference.com: std::unordered_map&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Technology"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/what-is-a-hash-map-hashing-concepts.webp" width="1200"/><media:title type="plain">What is a Hash Map? Deep Dive into Hashing Concepts Unveiled</media:title><media:description type="plain">A comprehensive guide on what is a Hash Map, exploring its inner workings, hashing concepts, collision resolution, and real-world applications.</media:description></entry><entry><title>How to Implement a Binary Search Tree in Python: A Deep Dive</title><link href="https://analyticsdrive.tech/how-to-implement-binary-search-tree-python/" rel="alternate"/><published>2026-03-22T21:33:00+05:30</published><updated>2026-03-22T21:33:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-22:/how-to-implement-binary-search-tree-python/</id><summary type="html">&lt;p&gt;Master Python's Binary Search Tree (BST) implementation. Explore its structure, core operations, and practical applications for efficient data management in ...&lt;/p&gt;</summary><content type="html">&lt;p&gt;Data structures are the backbone of efficient software development, and among the most fundamental yet powerful is the &lt;a href="https://analyticsdrive.tech/binary-search-tree/"&gt;Binary Search Tree&lt;/a&gt; (BST). Understanding and being able to &lt;strong&gt;implement a Binary Search Tree in Python&lt;/strong&gt; is a critical skill for any serious programmer, forming the basis for more advanced data management techniques and proving indispensable in various computational tasks. This deep dive will explore its structure, mechanics, and practical applications, providing you with a robust understanding and a comprehensive guide to building your own.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#understanding-the-binary-search-tree-bst"&gt;Understanding the Binary Search Tree (BST)&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-a-binary-search-tree"&gt;What is a Binary Search Tree?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#why-are-bsts-important"&gt;Why are BSTs Important?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-concepts-and-terminology"&gt;Core Concepts and Terminology&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#node-structure"&gt;Node Structure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#root-parent-child-leaf"&gt;Root, Parent, Child, Leaf&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#height-depth-level"&gt;Height, Depth, Level&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#how-to-implement-a-binary-search-tree-in-python"&gt;How to Implement a Binary Search Tree in Python&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#designing-the-bst-class"&gt;Designing the BST Class&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#insertion-operation-insert"&gt;Insertion Operation (insert)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#search-operation-search"&gt;Search Operation (search)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#deletion-operation-delete"&gt;Deletion Operation (delete)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#tree-traversal-techniques"&gt;Tree Traversal Techniques&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#in-order-traversal"&gt;In-order Traversal&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#pre-order-traversal"&gt;Pre-order Traversal&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#post-order-traversal"&gt;Post-order Traversal&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#level-order-traversal-breadth-first-search"&gt;Level-order Traversal (Breadth-First Search)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#balancing-bsts-a-critical-consideration"&gt;Balancing BSTs: A Critical Consideration&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-problem-of-skewed-trees"&gt;The Problem of Skewed Trees&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#introduction-to-self-balancing-bsts"&gt;Introduction to Self-Balancing BSTs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-binary-search-trees"&gt;Real-World Applications of Binary Search Trees&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#database-indexing"&gt;Database Indexing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#file-systems"&gt;File Systems&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#data-compression"&gt;Data Compression&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#game-development"&gt;Game Development&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#compiler-design"&gt;Compiler Design&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#network-routing"&gt;Network Routing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#dictionary-and-spell-checkers"&gt;Dictionary and Spell Checkers&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#performance-analysis-time-and-space-complexity"&gt;Performance Analysis: Time and Space Complexity&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#average-case-balanced-bst"&gt;Average Case (Balanced BST)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#worst-case-skewed-bst"&gt;Worst Case (Skewed BST)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-pitfalls-and-best-practices"&gt;Common Pitfalls and Best Practices&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#handling-duplicates"&gt;Handling Duplicates&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#recursion-depth-limits"&gt;Recursion Depth Limits&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#memory-overhead"&gt;Memory Overhead&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#edge-cases-and-testing"&gt;Edge Cases and Testing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id="understanding-the-binary-search-tree-bst"&gt;Understanding the Binary Search Tree (BST)&lt;/h2&gt;
&lt;p&gt;Before we delve into the intricacies of coding, it's crucial to grasp what a Binary Search Tree is and why it holds such a prominent place in computer science. It's not just an abstract concept; it's a practical tool for organizing data.&lt;/p&gt;
&lt;h3 id="what-is-a-binary-search-tree"&gt;What is a Binary Search Tree?&lt;/h3&gt;
&lt;p&gt;A Binary Search Tree is a hierarchical, node-based data structure that stores data in a way that makes searching, insertion, and deletion operations highly efficient in most cases. Each node in a BST contains a value, and it can have at most two children: a left child and a right child. The defining property of a BST is its strict ordering:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The value of a node is always greater than or equal to any value in its left subtree.&lt;/li&gt;
&lt;li&gt;The value of a node is always less than any value in its right subtree.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This ordering principle is what enables its search efficiency. Think of it like a highly organized physical dictionary where every word is strategically placed. If you're looking for "apple," you know it will be before "banana," and after "aardvark," guiding your search process directly to the relevant section.&lt;/p&gt;
&lt;p&gt;Consider a simple example: if the root node holds the value &lt;code&gt;10&lt;/code&gt;, then all nodes in its left subtree will have values less than &lt;code&gt;10&lt;/code&gt;, and all nodes in its right subtree will have values greater than or equal to &lt;code&gt;10&lt;/code&gt;. This rule applies recursively to every node in the tree.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Characteristics of a BST:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Hierarchical Structure:&lt;/strong&gt; Data is organized in levels, starting from a single root node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Node-Based:&lt;/strong&gt; Each element (node) stores a value and references to its children.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ordered Property:&lt;/strong&gt; Values are arranged such that left children are smaller, and right children are larger (or equal).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No Cycles:&lt;/strong&gt; There's always a unique path from the root to any other node.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="why-are-bsts-important"&gt;Why are BSTs Important?&lt;/h3&gt;
&lt;p&gt;The importance of BSTs stems from their ability to combine the advantages of a sorted array and a linked list. Like sorted arrays, they allow for efficient searching (on average, logarithmic time complexity). Like &lt;a href="/linked-lists-python-deep-dive-tutorial-data-structures/"&gt;linked lists in Python&lt;/a&gt;, they permit efficient insertion and deletion of elements (also logarithmic time on average) without reorganizing the entire data structure.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key advantages include:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Efficient Searching:&lt;/strong&gt; On average, finding an item takes &lt;code&gt;O(log n)&lt;/code&gt; time, which is significantly faster than &lt;code&gt;O(n)&lt;/code&gt; for unsorted lists or arrays when &lt;code&gt;n&lt;/code&gt; (the number of items) is large. For instance, searching 1,000,000 items in a balanced BST might take around 20 comparisons, whereas a linear scan would take up to 1,000,000 comparisons.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficient Insertion and Deletion:&lt;/strong&gt; Adding or removing elements also takes &lt;code&gt;O(log n)&lt;/code&gt; time on average, without the need for costly array reallocations or shifts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ordered Data Retrieval:&lt;/strong&gt; In-order traversal of a BST yields elements in sorted order, making it useful for scenarios requiring sorted data output.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Foundation for Advanced Structures:&lt;/strong&gt; BSTs are the conceptual basis for more complex and robust data structures like AVL trees and Red-Black trees, which self-balance to guarantee &lt;code&gt;O(log n)&lt;/code&gt; performance even in worst-case scenarios. These advanced trees are used extensively in databases and operating systems. For a broader understanding of tree structures, consider our guide on &lt;a href="/demystifying-binary-trees-structure-traversal-use/"&gt;Demystifying Binary Trees&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dynamic Data Handling:&lt;/strong&gt; Unlike static arrays, BSTs can grow or shrink dynamically, adapting to changing data requirements without fixed size constraints.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Understanding BSTs is a stepping stone to mastering many advanced data structures and algorithms, and it's a frequently tested concept in technical interviews.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="core-concepts-and-terminology"&gt;Core Concepts and Terminology&lt;/h2&gt;
&lt;p&gt;To effectively work with and implement a Binary Search Tree, it's essential to be familiar with its fundamental components and the terminology used to describe them.&lt;/p&gt;
&lt;h3 id="node-structure"&gt;Node Structure&lt;/h3&gt;
&lt;p&gt;The basic building block of any tree data structure, including a BST, is the &lt;strong&gt;Node&lt;/strong&gt;. Each node encapsulates the data element and contains pointers (or references, in Python) to other nodes.&lt;/p&gt;
&lt;p&gt;In the context of a BST, a node typically consists of:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Value (or Key):&lt;/strong&gt; The actual data stored in the node. This value is used for comparison during search and insertion operations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Left Child Pointer:&lt;/strong&gt; A reference to the root of the left subtree. If the node has no left child, this pointer is &lt;code&gt;None&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Right Child Pointer:&lt;/strong&gt; A reference to the root of the right subtree. If the node has no right child, this pointer is &lt;code&gt;None&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here’s how you would represent a &lt;code&gt;Node&lt;/code&gt; class in Python:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__str__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__repr__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Node(&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;)&amp;quot;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This simple &lt;code&gt;Node&lt;/code&gt; class provides a &lt;code&gt;key&lt;/code&gt; to store the data and initializes &lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt; child pointers to &lt;code&gt;None&lt;/code&gt;, indicating no children initially. The &lt;code&gt;__str__&lt;/code&gt; and &lt;code&gt;__repr__&lt;/code&gt; methods are added for convenient printing and debugging.&lt;/p&gt;
&lt;h3 id="root-parent-child-leaf"&gt;Root, Parent, Child, Leaf&lt;/h3&gt;
&lt;p&gt;These terms describe the relationships between nodes within the tree structure:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Root:&lt;/strong&gt; The topmost node in the tree. A tree can only have one root node, and it has no parent. All operations on the tree typically begin at the root. If a tree is empty, it has no root.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Parent:&lt;/strong&gt; Any node that has one or more children is called a parent node. For example, in a tree where node &lt;code&gt;A&lt;/code&gt; has children &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt;, &lt;code&gt;A&lt;/code&gt; is the parent of &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Child:&lt;/strong&gt; A node directly connected to another node one level below it. For example, if node &lt;code&gt;A&lt;/code&gt; is the parent of &lt;code&gt;B&lt;/code&gt;, then &lt;code&gt;B&lt;/code&gt; is a child of &lt;code&gt;A&lt;/code&gt;. A node can be a left child or a right child.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Leaf (or External Node):&lt;/strong&gt; A node that has no children. These nodes are at the "ends" of the tree branches.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Internal Node:&lt;/strong&gt; Any node that is not a leaf node (i.e., it has at least one child).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Subtree:&lt;/strong&gt; A portion of a tree that can itself be considered a tree. Every node in a tree is the root of a subtree consisting of itself and all its descendants.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="height-depth-level"&gt;Height, Depth, Level&lt;/h3&gt;
&lt;p&gt;These terms quantify the vertical dimensions of a tree:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Depth of a Node:&lt;/strong&gt; The number of edges from the root node to that specific node. The root node has a depth of 0.&lt;ul&gt;
&lt;li&gt;Example: If &lt;code&gt;Root&lt;/code&gt; -&amp;gt; &lt;code&gt;Node A&lt;/code&gt; -&amp;gt; &lt;code&gt;Node B&lt;/code&gt;, the depth of &lt;code&gt;Node B&lt;/code&gt; is 2.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Height of a Node:&lt;/strong&gt; The number of edges on the longest path from that node to a leaf node. Leaf nodes have a height of 0.&lt;ul&gt;
&lt;li&gt;Example: If &lt;code&gt;Node A&lt;/code&gt; has a leaf child &lt;code&gt;Node B&lt;/code&gt;, the height of &lt;code&gt;Node A&lt;/code&gt; is 1. If &lt;code&gt;Node A&lt;/code&gt; has no children, its height is 0.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Height of a Tree:&lt;/strong&gt; The height of its root node. This represents the longest path from the root to any leaf in the entire tree. A tree with only one node (the root) has a height of 0. An empty tree conventionally has a height of -1.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Level of a Node:&lt;/strong&gt; Similar to depth, but often used interchangeably. Level 0 is the root, Level 1 contains its children, Level 2 contains their children, and so on.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Understanding these concepts is fundamental for visualizing and manipulating BSTs, especially when discussing algorithms like tree traversal or balancing.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="how-to-implement-a-binary-search-tree-in-python"&gt;How to Implement a Binary Search Tree in Python&lt;/h2&gt;
&lt;p&gt;Now, let's get into the practical aspect: building a &lt;code&gt;BinarySearchTree&lt;/code&gt; class in Python. We'll start with the basic structure and then implement the core operations: insertion, searching, and deletion.&lt;/p&gt;
&lt;h3 id="designing-the-bst-class"&gt;Designing the BST Class&lt;/h3&gt;
&lt;p&gt;Our &lt;code&gt;BinarySearchTree&lt;/code&gt; class will encapsulate the tree's overall structure and provide methods for its operations. It will primarily manage the &lt;code&gt;root&lt;/code&gt; node of the tree.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BinarySearchTree&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;  &lt;span class="c1"&gt;# To keep track of the number of nodes&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__len__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__iter__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# We&amp;#39;ll implement an in-order traversal for iteration later&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_traversal_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_inorder_traversal_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_traversal_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;
            &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_traversal_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation of the &lt;code&gt;BinarySearchTree&lt;/code&gt; class:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;__init__(self)&lt;/code&gt;:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;code&gt;self.root = None&lt;/code&gt;: Initializes the tree as empty. The &lt;code&gt;root&lt;/code&gt; will point to the first node inserted.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;self.size = 0&lt;/code&gt;: Keeps track of the total number of nodes in the tree. This can be useful for various applications.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;__len__(self)&lt;/code&gt;:&lt;/strong&gt; Allows using &lt;code&gt;len(bst_instance)&lt;/code&gt; to get the number of nodes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;__iter__(self)&lt;/code&gt; and &lt;code&gt;_inorder_traversal_iter(self, node)&lt;/code&gt;:&lt;/strong&gt; These methods enable the &lt;code&gt;BinarySearchTree&lt;/code&gt; object to be iterable (e.g., using &lt;code&gt;for key in bst:&lt;/code&gt;). We've chosen in-order traversal for this, which naturally yields keys in sorted order. We will discuss traversals in more detail later.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="insertion-operation-insert"&gt;Insertion Operation (&lt;code&gt;insert&lt;/code&gt;)&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;insert&lt;/code&gt; operation adds a new key into the BST while maintaining its ordered property. This process typically starts at the root and recursively or iteratively moves down the tree until an appropriate spot (a &lt;code&gt;None&lt;/code&gt; child link) is found.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Algorithm for Insertion:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Start at the root:&lt;/strong&gt; If the tree is empty, the new key becomes the root.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Compare keys:&lt;/strong&gt; If the new key is less than the current node's key, go to the left child. If it's greater than or equal to, go to the right child.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursively traverse:&lt;/strong&gt; Repeat step 2 until a &lt;code&gt;None&lt;/code&gt; child pointer is encountered.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Insert:&lt;/strong&gt; Create a new node with the key and attach it at that &lt;code&gt;None&lt;/code&gt; position.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We can implement &lt;code&gt;insert&lt;/code&gt; using a helper recursive function to simplify the logic.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# We need to ensure size is only incremented if a new node is actually added&lt;/span&gt;
        &lt;span class="n"&gt;old_size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;old_size&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# If recursive call didn&amp;#39;t increment (i.e., duplicate handler)&lt;/span&gt;
            &lt;span class="c1"&gt;# This specific implementation always increments size, so no need for this check here&lt;/span&gt;
            &lt;span class="c1"&gt;# For a strict &amp;quot;no duplicates&amp;quot; policy, this logic would change.&lt;/span&gt;
            &lt;span class="c1"&gt;# For our current logic (duplicates go right), size always increments for a new physical node.&lt;/span&gt;
            &lt;span class="k"&gt;pass&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Increment size when a new node is created&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# key &amp;gt;= node.key, duplicates go to the right&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Time Complexity for Insertion:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Average Case:&lt;/strong&gt; &lt;code&gt;O(log n)&lt;/code&gt;. This occurs when the tree is relatively balanced, meaning the path from the root to any leaf is roughly logarithmic with respect to &lt;code&gt;n&lt;/code&gt;. Each comparison roughly halves the remaining search space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Worst Case:&lt;/strong&gt; &lt;code&gt;O(n)&lt;/code&gt;. This happens when the tree becomes skewed (degenerate), resembling a linked list. For example, inserting elements in strictly increasing or decreasing order will lead to this. In such a scenario, every insertion might require traversing almost all existing nodes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="search-operation-search"&gt;Search Operation (&lt;code&gt;search&lt;/code&gt;)&lt;/h3&gt;
&lt;p&gt;Searching for a key in a BST leverages its ordered property to quickly locate the desired node or determine its absence.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Algorithm for Searching:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Start at the root.&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Compare:&lt;/strong&gt; If the current node's key matches the target key, the key is found.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Navigate:&lt;/strong&gt; If the target key is less than the current node's key, move to the left child. If it's greater, move to the right child.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Repeat:&lt;/strong&gt; Continue until the key is found or a &lt;code&gt;None&lt;/code&gt; node is reached (meaning the key is not in the tree).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Here's the Python implementation:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;  &lt;span class="c1"&gt;# Key not found&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;   &lt;span class="c1"&gt;# Key found&lt;/span&gt;
        &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# key &amp;gt; node.key&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="c1"&gt;# Helper to return the node itself, not just boolean&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Time Complexity for Searching:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Average Case:&lt;/strong&gt; &lt;code&gt;O(log n)&lt;/code&gt;. Similar to insertion, the search path is logarithmic in a balanced tree.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Worst Case:&lt;/strong&gt; &lt;code&gt;O(n)&lt;/code&gt;. If the tree is skewed, searching might require traversing all nodes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="deletion-operation-delete"&gt;Deletion Operation (&lt;code&gt;delete&lt;/code&gt;)&lt;/h3&gt;
&lt;p&gt;Deletion is the most complex of the primary BST operations because it must not only remove a node but also reorganize the tree to maintain the BST property. There are three main cases to consider, based on how many children the node to be deleted has:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Node is a Leaf (0 children):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Simply remove the node by setting its parent's pointer to &lt;code&gt;None&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Node has 1 Child:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Replace the node with its sole child. The child's subtree takes the place of the deleted node.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Node has 2 Children:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;This is the most involved case. The node cannot simply be removed without breaking the BST property. Instead, we find its &lt;strong&gt;in-order successor&lt;/strong&gt; (the smallest node in its right subtree) or its &lt;strong&gt;in-order predecessor&lt;/strong&gt; (the largest node in its left subtree).&lt;/li&gt;
&lt;li&gt;Replace the deleted node's key with the key of the in-order successor.&lt;/li&gt;
&lt;li&gt;Then, delete the in-order successor from its original position (which will fall into case 0 or 1, as an in-order successor has at most one child).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Algorithm for Deletion:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A recursive approach is often clearest for deletion.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;delete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;initial_size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="c1"&gt;# Only decrement size if the root changed or a node was actually removed by the recursive call&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;initial_size&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="c1"&gt;# This is a bit tricky with duplicates. A more robust way is to pass a flag from _delete_recursive&lt;/span&gt;
            &lt;span class="c1"&gt;# to indicate if a deletion occurred. For this example, let&amp;#39;s simplify and assume the key exists.&lt;/span&gt;
            &lt;span class="k"&gt;pass&lt;/span&gt; &lt;span class="c1"&gt;# The _delete_recursive implicitly handles size decrement through self.size -= 1 when a node is removed.&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;  &lt;span class="c1"&gt;# Key not found&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# This is the node to be deleted&lt;/span&gt;

            &lt;span class="c1"&gt;# Case 1 &amp;amp; 2: Node with 0 or 1 child&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Node removed&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;
            &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Node removed&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;

            &lt;span class="c1"&gt;# Case 3: Node with 2 children&lt;/span&gt;
            &lt;span class="n"&gt;temp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_find_min_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Find in-order successor&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="c1"&gt;# Copy successor&amp;#39;s key to this node&lt;/span&gt;
            &lt;span class="c1"&gt;# Delete the in-order successor from the right subtree.&lt;/span&gt;
            &lt;span class="c1"&gt;# The size decrement happens in the recursive call for `temp.key`.&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_find_min_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Time Complexity for Deletion:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Average Case:&lt;/strong&gt; &lt;code&gt;O(log n)&lt;/code&gt;. The process of finding the node to delete and potentially its in-order successor involves traversing a path in the tree, which is logarithmic in a balanced tree.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Worst Case:&lt;/strong&gt; &lt;code&gt;O(n)&lt;/code&gt;. If the tree is skewed, traversing to find the node or its successor can take &lt;code&gt;O(n)&lt;/code&gt; time.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Putting it all together (complete BST class):&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__str__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__repr__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Node(&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;)&amp;quot;&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BinarySearchTree&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__len__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__iter__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_traversal_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_inorder_traversal_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_traversal_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;yield&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;
            &lt;span class="k"&gt;yield from&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_traversal_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# We need to ensure size is only incremented if a new node is actually added&lt;/span&gt;
        &lt;span class="n"&gt;old_size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;old_size&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# If recursive call didn&amp;#39;t increment (i.e., duplicate handler)&lt;/span&gt;
            &lt;span class="c1"&gt;# This specific implementation always increments size, so no need for this check here&lt;/span&gt;
            &lt;span class="c1"&gt;# For a strict &amp;quot;no duplicates&amp;quot; policy, this logic would change.&lt;/span&gt;
            &lt;span class="c1"&gt;# For our current logic (duplicates go right), size always increments for a new physical node.&lt;/span&gt;
            &lt;span class="k"&gt;pass&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Increment size when a new node is created&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# key &amp;gt;= node.key, duplicates go to the right&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
        &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;delete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;initial_size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="c1"&gt;# Only decrement size if the root changed or a node was actually removed by the recursive call&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;initial_size&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_get_node_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="c1"&gt;# This is a bit tricky with duplicates. A more robust way is to pass a flag from _delete_recursive&lt;/span&gt;
            &lt;span class="c1"&gt;# to indicate if a deletion occurred. For this example, let&amp;#39;s simplify and assume the key exists.&lt;/span&gt;
            &lt;span class="k"&gt;pass&lt;/span&gt; &lt;span class="c1"&gt;# The _delete_recursive implicitly handles size decrement through self.size -= 1 when a node is removed.&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;  &lt;span class="c1"&gt;# Key not found&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# This is the node to be deleted&lt;/span&gt;

            &lt;span class="c1"&gt;# Case 1 &amp;amp; 2: Node with 0 or 1 child&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Node removed&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;
            &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Node removed&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;

            &lt;span class="c1"&gt;# Case 3: Node with 2 children&lt;/span&gt;
            &lt;span class="n"&gt;temp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_find_min_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Find in-order successor&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="c1"&gt;# Copy successor&amp;#39;s key to this node&lt;/span&gt;
            &lt;span class="c1"&gt;# Delete the in-order successor from the right subtree.&lt;/span&gt;
            &lt;span class="c1"&gt;# The size decrement happens in the recursive call for `temp.key`.&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_find_min_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;hr&gt;
&lt;h2 id="tree-traversal-techniques"&gt;Tree Traversal Techniques&lt;/h2&gt;
&lt;p&gt;Once a BST is built, we often need to visit all its nodes in a specific order. This process is called tree traversal. There are four common ways to traverse a BST: in-order, pre-order, post-order, and level-order.&lt;/p&gt;
&lt;h3 id="in-order-traversal"&gt;In-order Traversal&lt;/h3&gt;
&lt;p&gt;In-order traversal visits nodes in the order: &lt;strong&gt;Left subtree -&amp;gt; Root -&amp;gt; Right subtree&lt;/strong&gt;.
When performed on a Binary Search Tree, in-order traversal yields the keys in ascending (sorted) order.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;inorder_traversal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;elements&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_inorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Example Output:&lt;/strong&gt; For a BST with keys &lt;code&gt;[8, 3, 10, 1, 6, 14, 4, 7, 13]&lt;/code&gt;, an in-order traversal would produce &lt;code&gt;[1, 3, 4, 6, 7, 8, 10, 13, 14]&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="pre-order-traversal"&gt;Pre-order Traversal&lt;/h3&gt;
&lt;p&gt;Pre-order traversal visits nodes in the order: &lt;strong&gt;Root -&amp;gt; Left subtree -&amp;gt; Right subtree&lt;/strong&gt;.
This traversal is useful for creating a copy of the tree or for prefix expressions.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;preorder_traversal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;elements&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_preorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_preorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_preorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt; &lt;span class="n"&gt;_preorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Example Output:&lt;/strong&gt; For the same BST, a pre-order traversal might produce &lt;code&gt;[8, 3, 1, 6, 4, 7, 10, 14, 13]&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="post-order-traversal"&gt;Post-order Traversal&lt;/h3&gt;
&lt;p&gt;Post-order traversal visits nodes in the order: &lt;strong&gt;Left subtree -&amp;gt; Right subtree -&amp;gt; Root&lt;/strong&gt;.
This traversal is often used for deleting nodes in a tree or for postfix expressions.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;postorder_traversal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;elements&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_postorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_postorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_postorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_postorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Example Output:&lt;/strong&gt; For the same BST, a post-order traversal might produce &lt;code&gt;[1, 4, 7, 6, 3, 13, 14, 10, 8]&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="level-order-traversal-breadth-first-search"&gt;Level-order Traversal (Breadth-First Search)&lt;/h3&gt;
&lt;p&gt;Unlike the previous three, level-order traversal (also known as Breadth-First Search or BFS) visits nodes level by level, starting from the root and moving horizontally. This requires a queue data structure.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;levelorder_traversal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;elements&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;

        &lt;span class="n"&gt;queue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Dequeue&lt;/span&gt;
            &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Enqueue left child&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Enqueue right child&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Example Output:&lt;/strong&gt; For the same BST, a level-order traversal might produce &lt;code&gt;[8, 3, 10, 1, 6, 14, 4, 7, 13]&lt;/code&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="balancing-bsts-a-critical-consideration"&gt;Balancing BSTs: A Critical Consideration&lt;/h2&gt;
&lt;p&gt;While the average-case performance of BSTs is excellent (&lt;code&gt;O(log n)&lt;/code&gt;), their worst-case performance (&lt;code&gt;O(n)&lt;/code&gt;) can negate these benefits. This degradation typically occurs when the tree becomes unbalanced or "skewed."&lt;/p&gt;
&lt;h3 id="the-problem-of-skewed-trees"&gt;The Problem of Skewed Trees&lt;/h3&gt;
&lt;p&gt;A skewed tree is one where all nodes are inserted in a strictly ascending or descending order. For example, if you insert &lt;code&gt;1, 2, 3, 4, 5&lt;/code&gt; into an empty BST, each new node will be placed as the right child of the previous one, forming a structure that essentially behaves like a linked list.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Consequences of a Skewed Tree:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Degraded Performance:&lt;/strong&gt; Search, insertion, and deletion operations, which were &lt;code&gt;O(log n)&lt;/code&gt; on average, now take &lt;code&gt;O(n)&lt;/code&gt; time. This eliminates the primary advantage of using a BST over a simple sorted array or linked list.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Increased Memory Usage:&lt;/strong&gt; While each node itself isn't larger, the recursive call stack for operations can become very deep, potentially leading to stack overflow errors in languages with strict recursion depth limits (like Python, which has a default limit of 1000 or 3000 depending on the environment).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For instance, Python's default recursion limit can be increased using &lt;code&gt;sys.setrecursionlimit()&lt;/code&gt;, but this is merely a workaround for a fundamentally inefficient tree structure.&lt;/p&gt;
&lt;h3 id="introduction-to-self-balancing-bsts"&gt;Introduction to Self-Balancing BSTs&lt;/h3&gt;
&lt;p&gt;To overcome the limitations of skewed BSTs, advanced versions called &lt;strong&gt;self-balancing Binary Search Trees&lt;/strong&gt; were developed. These trees automatically perform rotations or other restructuring operations to maintain a relatively balanced height, ensuring that operations consistently achieve &lt;code&gt;O(log n)&lt;/code&gt; time complexity.&lt;/p&gt;
&lt;p&gt;The most common self-balancing BSTs include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;AVL Trees:&lt;/strong&gt; Named after their inventors, Adelson-Velsky and Landis, AVL trees maintain a balance factor (the difference in height between the left and right subtrees of any node) of -1, 0, or 1. If this factor exceeds these limits, the tree performs single or double rotations to rebalance itself.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Red-Black Trees:&lt;/strong&gt; These are slightly more complex but more commonly used in practice (e.g., in Java's &lt;code&gt;TreeMap&lt;/code&gt; and &lt;code&gt;TreeSet&lt;/code&gt;, and Linux kernel schedulers). Red-Black trees maintain balance by assigning a "color" (red or black) to each node and enforcing five specific properties that guarantee the tree remains approximately balanced.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;While implementing self-balancing BSTs is beyond the scope of this article (as it focuses on the fundamental BST), understanding their existence and purpose is crucial. They are the production-grade solution when consistent &lt;code&gt;O(log n)&lt;/code&gt; performance is a non-negotiable requirement. For many typical applications, a basic BST is sufficient, but for performance-critical systems, self-balancing variants are essential.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="real-world-applications-of-binary-search-trees"&gt;Real-World Applications of Binary Search Trees&lt;/h2&gt;
&lt;p&gt;Beyond academic exercises, Binary Search Trees and their variants power many systems we use daily. Their efficiency in maintaining ordered data makes them invaluable.&lt;/p&gt;
&lt;h3 id="database-indexing"&gt;Database Indexing&lt;/h3&gt;
&lt;p&gt;One of the most critical applications is in database indexing. Databases use structures like B-trees (a generalized form of BSTs where nodes can have more than two children) and B+ trees to index records. When you search for data in a large database, an index (often a B-tree) allows the database to locate the desired record in &lt;code&gt;O(log n)&lt;/code&gt; time, rather than scanning millions of records linearly. This is fundamental to the speed and scalability of modern &lt;a href="https://analyticsdrive.tech/relational-databases/"&gt;relational databases&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Data Example (conceptual):&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;Table: Users
Columns: UserID (Primary Key), Username, Email

B-tree Index on UserID:
Root: 50
Children: [20, 80]
Left child subtree (keys &amp;lt; 50): [10, 30]
Right child subtree (keys &amp;gt;= 50): [60, 90]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;When you query &lt;code&gt;SELECT * FROM Users WHERE UserID = 75;&lt;/code&gt;, the database uses the B-tree to quickly navigate to the relevant data block, significantly reducing disk I/O.&lt;/p&gt;
&lt;h3 id="file-systems"&gt;File Systems&lt;/h3&gt;
&lt;p&gt;File systems on operating systems (like NTFS, HFS+, ext4) often use tree-like structures to organize directories and files. While not always pure BSTs, the hierarchical nature and the need for efficient lookup by name or path often involve principles derived from tree data structures, including variations for quick file location and management. Operations like finding a file, listing directory contents, or deleting a file can leverage these structures.&lt;/p&gt;
&lt;h3 id="data-compression"&gt;Data Compression&lt;/h3&gt;
&lt;p&gt;Techniques like Huffman coding, which is used in many data compression algorithms (e.g., in JPEG and MP3 formats), rely on binary trees. A Huffman tree is a binary tree where leaf nodes represent characters and their frequencies, and the path from the root to a leaf forms the character's unique binary code. More frequent characters get shorter codes, leading to compression. While not strictly a &lt;em&gt;search&lt;/em&gt; tree, it demonstrates the utility of binary tree structures in practical data manipulation.&lt;/p&gt;
&lt;h3 id="game-development"&gt;Game Development&lt;/h3&gt;
&lt;p&gt;In game development, spatial partitioning trees (like k-d trees, octrees, and bounding volume hierarchies, which are types of binary space partitioning (BSP) trees) are used to organize objects in 2D or 3D space. These trees allow game engines to efficiently:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Perform collision detection:&lt;/strong&gt; Quickly identify which objects are near each other and might collide, rather than checking every object against every other object.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Render scenes:&lt;/strong&gt; Determine which objects are visible to the camera (frustum culling) and optimize rendering order.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pathfinding:&lt;/strong&gt; Help AI agents navigate complex environments.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="compiler-design"&gt;Compiler Design&lt;/h3&gt;
&lt;p&gt;Compilers and interpreters use tree structures to represent the syntax of source code. An &lt;strong&gt;Abstract Syntax Tree (AST)&lt;/strong&gt; is a tree representation of the abstract syntactic structure of source code written in a programming language. Each node in the AST denotes a construct occurring in the source code. These trees are fundamental for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Parsing:&lt;/strong&gt; Analyzing the code's grammatical structure.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Semantic Analysis:&lt;/strong&gt; Checking for type errors and other logical inconsistencies.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Code Generation:&lt;/strong&gt; Translating the AST into machine code or intermediate representations.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="network-routing"&gt;Network Routing&lt;/h3&gt;
&lt;p&gt;In certain network routing algorithms, particularly for smaller, specialized networks, tree structures can be used to manage routing tables and efficiently determine the next hop for a data packet.&lt;/p&gt;
&lt;h3 id="dictionary-and-spell-checkers"&gt;Dictionary and Spell Checkers&lt;/h3&gt;
&lt;p&gt;While &lt;a href="/hash-tables-comprehensive-guide-real-world-uses/"&gt;hash tables&lt;/a&gt; are also popular for dictionaries, BSTs can be used to store words for efficient lookup and suggestion. The sorted property of an in-order traversal allows for quick access to words lexicographically close to a given word, which can be useful for spell-checking and auto-completion features.&lt;/p&gt;
&lt;p&gt;These examples highlight that Binary Search Trees are not just theoretical constructs but robust, adaptable tools vital for the performance and structure of numerous software systems across diverse domains.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="performance-analysis-time-and-space-complexity"&gt;Performance Analysis: Time and Space Complexity&lt;/h2&gt;
&lt;p&gt;A crucial aspect of any data structure is understanding its performance characteristics, specifically its time and space complexity. This analysis, often expressed using &lt;a href="/big-o-notation-explained-beginner-guide-complexity/"&gt;Big O Notation&lt;/a&gt;, helps us predict how the data structure will behave with varying input sizes and informs decisions about when to use a BST.&lt;/p&gt;
&lt;h3 id="average-case-balanced-bst"&gt;Average Case (Balanced BST)&lt;/h3&gt;
&lt;p&gt;When a Binary Search Tree is balanced (i.e., its height is approximately &lt;code&gt;log n&lt;/code&gt;, where &lt;code&gt;n&lt;/code&gt; is the number of nodes), all primary operations exhibit excellent performance.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Search:&lt;/strong&gt; &lt;code&gt;O(log n)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Insertion:&lt;/strong&gt; &lt;code&gt;O(log n)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deletion:&lt;/strong&gt; &lt;code&gt;O(log n)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt; In a balanced BST, each comparison effectively halves the number of nodes that need to be considered. For a tree with &lt;code&gt;n&lt;/code&gt; nodes, the maximum number of comparisons to find a node is proportional to its height. If the tree is balanced, its height &lt;code&gt;h&lt;/code&gt; is approximately &lt;code&gt;log₂ n&lt;/code&gt;. For example, a tree with 1,024 nodes (&lt;code&gt;2^10&lt;/code&gt;) would have a height of about 10, meaning operations would take around 10 steps. This logarithmic growth makes BSTs incredibly efficient for large datasets, as &lt;code&gt;log n&lt;/code&gt; grows much slower than &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="worst-case-skewed-bst"&gt;Worst Case (Skewed BST)&lt;/h3&gt;
&lt;p&gt;As discussed earlier, a BST can degrade into a skewed tree (resembling a linked list) if elements are inserted in a strictly sorted or reverse-sorted order. In this scenario, the benefits of the tree structure are lost.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Search:&lt;/strong&gt; &lt;code&gt;O(n)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Insertion:&lt;/strong&gt; &lt;code&gt;O(n)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deletion:&lt;/strong&gt; &lt;code&gt;O(n)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt; In a completely skewed tree, the height &lt;code&gt;h&lt;/code&gt; becomes &lt;code&gt;n&lt;/code&gt;. Every operation, such as finding, inserting, or deleting a node, may require traversing almost all &lt;code&gt;n&lt;/code&gt; nodes from the root to the deepest leaf. This linear time complexity is equivalent to searching an unsorted array or a simple linked list, which is undesirable for large datasets. This is precisely why self-balancing BSTs like AVL trees and Red-Black trees were developed: to guarantee &lt;code&gt;O(log n)&lt;/code&gt; performance by preventing the worst-case scenario.&lt;/p&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;Space complexity refers to the amount of memory consumed by the data structure.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Node Storage:&lt;/strong&gt; &lt;code&gt;O(n)&lt;/code&gt;&lt;ul&gt;
&lt;li&gt;Each node stores its &lt;code&gt;key&lt;/code&gt;, a &lt;code&gt;left&lt;/code&gt; pointer, and a &lt;code&gt;right&lt;/code&gt; pointer. Regardless of the tree's balance, you always store &lt;code&gt;n&lt;/code&gt; nodes, so the total space required is proportional to the number of elements.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursion Stack (for recursive operations):&lt;/strong&gt; &lt;code&gt;O(h)&lt;/code&gt;&lt;ul&gt;
&lt;li&gt;For recursive operations like insertion, deletion, and traversal, the system uses a call stack. The maximum depth of this stack corresponds to the height &lt;code&gt;h&lt;/code&gt; of the tree.&lt;/li&gt;
&lt;li&gt;In the &lt;strong&gt;average case (balanced BST)&lt;/strong&gt;, &lt;code&gt;h = O(log n)&lt;/code&gt;, so the stack space is &lt;code&gt;O(log n)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;In the &lt;strong&gt;worst case (skewed BST)&lt;/strong&gt;, &lt;code&gt;h = O(n)&lt;/code&gt;, leading to &lt;code&gt;O(n)&lt;/code&gt; stack space, which can lead to &lt;code&gt;StackOverflowError&lt;/code&gt; for very large &lt;code&gt;n&lt;/code&gt; in languages with limited stack size. Iterative implementations can mitigate this by avoiding the recursion stack.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Summary of Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style="text-align: left;"&gt;Operation&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Average Case Time&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Worst Case Time&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Space Complexity&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Search&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(log n)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(n)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(1)&lt;/code&gt; (iterative), &lt;code&gt;O(h)&lt;/code&gt; (recursive)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Insertion&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(log n)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(n)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(1)&lt;/code&gt; (iterative), &lt;code&gt;O(h)&lt;/code&gt; (recursive)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Deletion&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(log n)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(n)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(1)&lt;/code&gt; (iterative), &lt;code&gt;O(h)&lt;/code&gt; (recursive)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Traversal&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(n)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(n)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(h)&lt;/code&gt; (recursive), &lt;code&gt;O(w)&lt;/code&gt; (BFS queue, &lt;code&gt;w&lt;/code&gt; = max width)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Note that traversal is always &lt;code&gt;O(n)&lt;/code&gt; because you must visit every node. The space complexity for traversal refers to the auxiliary space used (e.g., the recursion stack or the queue for BFS), not the storage of the tree itself.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="common-pitfalls-and-best-practices"&gt;Common Pitfalls and Best Practices&lt;/h2&gt;
&lt;p&gt;When working with Binary Search Trees, especially in Python, there are several considerations and best practices that can help prevent errors and ensure robust implementations.&lt;/p&gt;
&lt;h3 id="handling-duplicates"&gt;Handling Duplicates&lt;/h3&gt;
&lt;p&gt;The standard definition of a Binary Search Tree often implies that all keys are unique. However, in real-world scenarios, you might encounter duplicate keys. There are several strategies to handle them:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Ignore Duplicates:&lt;/strong&gt; When an insertion attempt is made with an existing key, simply do nothing (as implemented in our initial &lt;code&gt;insert&lt;/code&gt; method if &lt;code&gt;key == node.key&lt;/code&gt; branch was to &lt;code&gt;return node&lt;/code&gt;). This keeps the tree smaller and ensures uniqueness.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Store in Right Subtree:&lt;/strong&gt; Place duplicate keys in the right subtree (as implemented in our &lt;code&gt;_insert_recursive&lt;/code&gt; where &lt;code&gt;else&lt;/code&gt; branch handles &lt;code&gt;key &amp;gt;= node.key&lt;/code&gt;). This is a common and simple approach.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Store in Left Subtree:&lt;/strong&gt; Place duplicate keys in the left subtree.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Add a Count Attribute:&lt;/strong&gt; Modify the &lt;code&gt;Node&lt;/code&gt; class to store a &lt;code&gt;count&lt;/code&gt; for each key. When a duplicate key is inserted, increment its count instead of creating a new node. This is memory-efficient for many duplicates of the same key.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Linked List at Node:&lt;/strong&gt; For a more complex approach, each node could point to a linked list of all duplicate keys.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The choice depends on the specific requirements of your application. For consistency, it's vital to apply the chosen duplicate handling strategy consistently across all operations (insert, search, delete). For example, if duplicates are always in the right subtree, searching for a duplicate might need to continue into the right subtree even if the current node matches the key.&lt;/p&gt;
&lt;h3 id="recursion-depth-limits"&gt;Recursion Depth Limits&lt;/h3&gt;
&lt;p&gt;Python has a default recursion depth limit (typically 1000, though it can vary). If you're building a very deep BST (which happens in the worst-case &lt;code&gt;O(n)&lt;/code&gt; skewed scenario), recursive operations like insertion, search, or deletion can hit this limit, resulting in a &lt;code&gt;RecursionError&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Best Practices:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Iterative Implementations:&lt;/strong&gt; For production-grade or highly performance-critical BSTs that might become skewed, consider implementing the core operations (insert, search, delete) iteratively instead of recursively. Iterative approaches use explicit loops and a stack (or a queue for BFS) instead of the call stack, avoiding the recursion limit.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Increase Recursion Limit (with caution):&lt;/strong&gt; For development or competitive programming, you can temporarily increase Python's recursion limit using &lt;code&gt;sys.setrecursionlimit(new_limit)&lt;/code&gt;. However, this consumes more memory and should be done judiciously, as a very deep stack can still lead to memory issues.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use Self-Balancing Trees:&lt;/strong&gt; The most robust solution for managing deep trees and avoiding &lt;code&gt;O(n)&lt;/code&gt; worst-case behavior is to use a self-balancing BST (like an AVL tree or Red-Black tree). These structures guarantee a &lt;code&gt;log n&lt;/code&gt; height, thus limiting recursion depth.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="memory-overhead"&gt;Memory Overhead&lt;/h3&gt;
&lt;p&gt;Each &lt;code&gt;Node&lt;/code&gt; in a BST typically stores its &lt;code&gt;key&lt;/code&gt; and two references (&lt;code&gt;left&lt;/code&gt;, &lt;code&gt;right&lt;/code&gt;). In Python, these references are pointers to other objects. For small &lt;code&gt;keys&lt;/code&gt; (e.g., integers), the overhead of the two pointers can be significantly larger than the key itself.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Considerations:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Object Size:&lt;/strong&gt; Python objects have some inherent memory overhead. If you're storing a huge number of very small items, the memory footprint of a BST might be larger than a simple list or array, even if a list doesn't offer the same algorithmic efficiency.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Garbage Collection:&lt;/strong&gt; Python's garbage collector manages memory, but circular references (though less common in basic BSTs without explicit parent pointers) can sometimes complicate things.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Locality:&lt;/strong&gt; Nodes in a BST are typically not stored contiguously in memory, which can lead to poorer cache performance compared to arrays when traversing. For CPU-bound operations on massive datasets, this can be a factor.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For most typical applications, the &lt;code&gt;O(n)&lt;/code&gt; space complexity of a BST is perfectly acceptable, but it's good to be aware of the underlying memory characteristics, especially when dealing with extreme scale or highly constrained environments.&lt;/p&gt;
&lt;h3 id="edge-cases-and-testing"&gt;Edge Cases and Testing&lt;/h3&gt;
&lt;p&gt;Always thoroughly test your BST implementation with edge cases:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Empty tree:&lt;/strong&gt; Inserting into an empty tree.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Single node tree:&lt;/strong&gt; Deleting the root, inserting a child.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Skewed trees:&lt;/strong&gt; Inserting elements in sorted/reverse-sorted order.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deleting leaf nodes, nodes with one child, nodes with two children.&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Searching for existing and non-existing keys.&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Trees with only left children or only right children.&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Robust testing is crucial for verifying the correctness of the &lt;code&gt;insert&lt;/code&gt;, &lt;code&gt;search&lt;/code&gt;, and &lt;code&gt;delete&lt;/code&gt; operations, especially the intricate &lt;code&gt;delete&lt;/code&gt; method.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The Binary Search Tree is a foundational data structure that every aspiring and experienced developer should master. Its elegance lies in its ability to organize data hierarchically, enabling efficient search, insertion, and deletion operations with an average time complexity of &lt;code&gt;O(log n)&lt;/code&gt;. By understanding its core principles, node relationships, and the step-by-step process to &lt;strong&gt;implement a Binary Search Tree in Python&lt;/strong&gt;, you've equipped yourself with a versatile tool for managing dynamic, ordered data.&lt;/p&gt;
&lt;p&gt;While a basic BST offers significant performance advantages over linear data structures, it's crucial to acknowledge its vulnerability to becoming skewed, which can degrade performance to &lt;code&gt;O(n)&lt;/code&gt; in the worst case. This understanding naturally leads to the appreciation of self-balancing variants like AVL trees and Red-Black trees, which dynamically adjust their structure to guarantee &lt;code&gt;O(log n)&lt;/code&gt; performance.&lt;/p&gt;
&lt;p&gt;From database indexing and file systems to game development and compiler design, the principles of BSTs are woven into the fabric of modern software. Mastering its implementation in Python not only solidifies your grasp of essential computer science concepts but also provides a powerful building block for tackling more complex algorithmic challenges and creating highly performant applications. Continue your journey by exploring self-balancing trees and applying these concepts to solve real-world problems.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the main advantage of a Binary Search Tree (BST) over a sorted array?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A BST combines efficient searching (like a sorted array) with efficient insertion and deletion (unlike a sorted array, which requires shifting elements). On average, all these operations take &lt;code&gt;O(log n)&lt;/code&gt; time, making it superior for dynamic data.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: When would a Binary Search Tree perform poorly, and what is the solution?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A BST performs poorly (down to &lt;code&gt;O(n)&lt;/code&gt; complexity) if it becomes skewed, resembling a linked list. This typically happens when elements are inserted in strictly sorted order. The solution is to use self-balancing BSTs like AVL trees or Red-Black trees, which automatically rebalance to guarantee &lt;code&gt;O(log n)&lt;/code&gt; performance.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Are duplicates allowed in a standard Binary Search Tree? How are they handled?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The standard definition of a BST often implies unique keys. When duplicates are allowed, common strategies include always placing them in the right subtree, adding a &lt;code&gt;count&lt;/code&gt; attribute to the node to track multiple occurrences, or simply ignoring subsequent insertions of the same key. The chosen approach depends on the application's specific requirements.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/binary-search-tree-data-structure/"&gt;GeeksforGeeks: Binary Search Tree&lt;/a&gt; - A comprehensive resource covering BSTs with examples in various languages.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.programiz.com/dsa/binary-search-tree"&gt;Programiz: Binary Search Tree Data Structure&lt;/a&gt; - Another great tutorial with clear explanations and code.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Binary_search_tree"&gt;Wikipedia: Binary Search Tree&lt;/a&gt; - For a more formal, academic definition and properties.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.wiley.com/en-us/Data+Structures+and+Algorithms+in+Python-p-9781118290279"&gt;Data Structures and Algorithms in Python by Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser&lt;/a&gt; - A highly recommended textbook for in-depth learning of data structures.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://visualgo.net/en/bst"&gt;Visual Algo: Binary Search Tree Visualization&lt;/a&gt; - An interactive tool to visualize BST operations, helping to grasp complex concepts like deletion.&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Technology"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/how-to-implement-binary-search-tree-python.webp" width="1200"/><media:title type="plain">How to Implement a Binary Search Tree in Python: A Deep Dive</media:title><media:description type="plain">Master Python's Binary Search Tree (BST) implementation. Explore its structure, core operations, and practical applications for efficient data management in ...</media:description></entry><entry><title>Linked Lists in Python: A Deep Dive Tutorial into Data Structures</title><link href="https://analyticsdrive.tech/linked-lists-python-deep-dive-tutorial-data-structures/" rel="alternate"/><published>2026-03-22T00:20:00+05:30</published><updated>2026-03-22T00:20:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-22:/linked-lists-python-deep-dive-tutorial-data-structures/</id><summary type="html">&lt;p&gt;Explore Linked Lists in Python: A Deep Dive Tutorial covering fundamental concepts, implementations, complexity analysis, and real-world applications for tec...&lt;/p&gt;</summary><content type="html">&lt;p&gt;In the vast landscape of computer science, mastering fundamental data structures is paramount for any aspiring or seasoned developer. Among these, &lt;strong&gt;Linked Lists in Python: A Deep Dive Tutorial&lt;/strong&gt; stands out as a critical concept, offering a unique approach to managing dynamic data compared to conventional arrays. This comprehensive guide will take you through the intricacies of linked lists, from their basic building blocks to advanced implementations and practical applications, equipping you with the knowledge to ace coding interviews and build robust software solutions. We'll explore why understanding these dynamic structures is essential for efficient memory management and algorithm design in Python.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#understanding-what-linked-lists-are"&gt;Understanding What Linked Lists Are&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#analogies-for-understanding-linked-lists"&gt;Analogies for Understanding Linked Lists&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-anatomy-of-a-node"&gt;The Anatomy of a Node&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#structure-of-a-basic-node"&gt;Structure of a Basic Node&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-implementation-of-a-node"&gt;Python Implementation of a Node&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#exploring-different-types-of-linked-lists"&gt;Exploring Different Types of Linked Lists&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-singly-linked-list"&gt;1. Singly Linked List&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-doubly-linked-list"&gt;2. Doubly Linked List&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-circular-linked-list"&gt;3. Circular Linked List&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-linked-lists-in-python"&gt;Implementing Linked Lists in Python&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-linkedlist-class-structure"&gt;The LinkedList Class Structure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-operations-and-their-implementations"&gt;Core Operations and Their Implementations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-adding-nodes"&gt;1. Adding Nodes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-deleting-nodes"&gt;2. Deleting Nodes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-traversing-and-searching"&gt;3. Traversing and Searching&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-utility-operations"&gt;4. Utility Operations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#putting-it-all-together-a-complete-singly-linked-list-implementation"&gt;Putting It All Together: A Complete Singly Linked List Implementation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#linked-list-vs-array-when-to-use-which"&gt;Linked List vs. Array: When to Use Which?&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#key-differences"&gt;Key Differences&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#when-to-use-a-linked-list"&gt;When to Use a Linked List&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#when-to-use-an-array-python-list"&gt;When to Use an Array (Python List)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-linked-lists"&gt;Real-World Applications of Linked Lists&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-linked-list-interview-questions-and-patterns"&gt;Common Linked List Interview Questions and Patterns&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-reversing-a-linked-list"&gt;1. Reversing a Linked List&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-detecting-a-cycle-floyds-cycle-finding-algorithm"&gt;2. Detecting a Cycle (Floyd's Cycle-Finding Algorithm)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-finding-the-middle-of-a-linked-list"&gt;3. Finding the Middle of a Linked List&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-merging-two-sorted-linked-lists"&gt;4. Merging Two Sorted Linked Lists&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#advanced-concepts-and-optimizations"&gt;Advanced Concepts and Optimizations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#sentinel-dummy-nodes"&gt;Sentinel (Dummy) Nodes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#skip-lists"&gt;Skip Lists&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#memory-pool-allocation"&gt;Memory Pool Allocation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#pros-and-cons-of-linked-lists"&gt;Pros and Cons of Linked Lists&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#advantages-pros"&gt;Advantages (Pros)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#disadvantages-cons"&gt;Disadvantages (Cons)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#future-outlook-and-modern-relevance"&gt;Future Outlook and Modern Relevance&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="understanding-what-linked-lists-are"&gt;Understanding What Linked Lists Are&lt;/h2&gt;
&lt;p&gt;A linked list is a linear data structure, much like an array, but with a fundamentally different way of storing elements. Instead of storing data in contiguous memory locations, a linked list consists of a sequence of &lt;em&gt;nodes&lt;/em&gt;, where each node contains the data itself and a reference (or pointer) to the next node in the sequence. This non-contiguous storage is what gives linked lists their dynamic nature, allowing them to grow and shrink efficiently.&lt;/p&gt;
&lt;h3 id="analogies-for-understanding-linked-lists"&gt;Analogies for Understanding Linked Lists&lt;/h3&gt;
&lt;p&gt;To truly grasp the concept, let's consider a few analogies:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;A Scavenger Hunt:&lt;/strong&gt; Imagine you're on a scavenger hunt. Instead of a list of all locations, you receive the first clue. This clue tells you where to find the second clue, which tells you where to find the third, and so on, until you reach the final treasure. Each clue is like a node, holding a piece of information (the next location) and a pointer (the direction to that location).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A Train with Detachable Cars:&lt;/strong&gt; Think of a train where each car (node) holds passengers (data) and is connected to the next car by a coupling (pointer). You can easily add or remove cars anywhere in the middle without having to rebuild the entire train, unlike a fixed-length passenger bus (array).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A Chain of Paper Clips:&lt;/strong&gt; Each paper clip holds a piece of paper (data) and is hooked onto the next paper clip. If you want to add a new piece of paper, you just unhook two clips, insert the new one, and re-hook them. This is much easier than resizing a pre-made stack of papers.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These analogies highlight the key characteristic of linked lists: their flexibility in memory allocation and insertion/deletion operations, which often outperform arrays in specific scenarios.&lt;/p&gt;
&lt;h2 id="the-anatomy-of-a-node"&gt;The Anatomy of a Node&lt;/h2&gt;
&lt;p&gt;At the heart of every linked list is the &lt;code&gt;Node&lt;/code&gt;. Without a proper &lt;code&gt;Node&lt;/code&gt; class, you cannot construct a linked list. This class is remarkably simple yet incredibly powerful, defining the fundamental building block of our data structure.&lt;/p&gt;
&lt;h3 id="structure-of-a-basic-node"&gt;Structure of a Basic Node&lt;/h3&gt;
&lt;p&gt;A typical node in a singly linked list has two primary components:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;data&lt;/code&gt; (or &lt;code&gt;value&lt;/code&gt;):&lt;/strong&gt; This holds the actual information or object that the node is meant to store. It can be any Python data type: an integer, a string, an object, or even another data structure.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;next&lt;/code&gt;:&lt;/strong&gt; This is a reference (a pointer) to the subsequent node in the sequence. If a node is the last node in the list, its &lt;code&gt;next&lt;/code&gt; pointer will typically be &lt;code&gt;None&lt;/code&gt;, signifying the end of the list.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="python-implementation-of-a-node"&gt;Python Implementation of a Node&lt;/h3&gt;
&lt;p&gt;Let's see how we can implement this simple &lt;code&gt;Node&lt;/code&gt; class in Python:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;    A basic Node class for a singly linked list.&lt;/span&gt;
&lt;span class="sd"&gt;    Each node stores data and a reference to the next node.&lt;/span&gt;
&lt;span class="sd"&gt;    &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;  &lt;span class="c1"&gt;# The data stored in the node&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;  &lt;span class="c1"&gt;# Pointer to the next node, initialized to None&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;In this implementation:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;__init__&lt;/code&gt; method is the constructor. When you create a new &lt;code&gt;Node&lt;/code&gt; object, you pass the &lt;code&gt;data&lt;/code&gt; it should hold.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;self.data&lt;/code&gt; is assigned the &lt;code&gt;data&lt;/code&gt; provided.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;self.next&lt;/code&gt; is initialized to &lt;code&gt;None&lt;/code&gt;. This is crucial because when a new node is created, it doesn't initially point to any other node. It will be linked later when inserted into a list.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This &lt;code&gt;Node&lt;/code&gt; class is foundational. Every operation you perform on a linked list—insertion, deletion, traversal, searching—ultimately involves manipulating these &lt;code&gt;Node&lt;/code&gt; objects and their &lt;code&gt;next&lt;/code&gt; pointers.&lt;/p&gt;
&lt;h2 id="exploring-different-types-of-linked-lists"&gt;Exploring Different Types of Linked Lists&lt;/h2&gt;
&lt;p&gt;While the basic concept of a node remains consistent, linked lists can be categorized into several types based on how their nodes are connected. Each type offers distinct advantages and is suited for different use cases.&lt;/p&gt;
&lt;h3 id="1-singly-linked-list"&gt;1. Singly Linked List&lt;/h3&gt;
&lt;p&gt;This is the most straightforward type and what we've primarily discussed so far.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Nodes are linked in a single direction.&lt;/li&gt;
&lt;li&gt;Each node has a &lt;code&gt;data&lt;/code&gt; field and a &lt;code&gt;next&lt;/code&gt; pointer pointing to the next node.&lt;/li&gt;
&lt;li&gt;Traversal is only possible from head to tail.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;next&lt;/code&gt; pointer of the last node is &lt;code&gt;None&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Use Cases:&lt;/strong&gt; Implementing stacks, queues, and representing polynomial expressions.&lt;/p&gt;
&lt;h3 id="2-doubly-linked-list"&gt;2. Doubly Linked List&lt;/h3&gt;
&lt;p&gt;Doubly linked lists enhance the basic singly linked list by adding a backward reference.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Nodes are linked in two directions (forward and backward).&lt;/li&gt;
&lt;li&gt;Each node has &lt;code&gt;data&lt;/code&gt;, a &lt;code&gt;next&lt;/code&gt; pointer to the successor, and a &lt;code&gt;prev&lt;/code&gt; (or &lt;code&gt;previous&lt;/code&gt;) pointer to the predecessor.&lt;/li&gt;
&lt;li&gt;Traversal is possible in both forward and backward directions.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;prev&lt;/code&gt; pointer of the first node (head) and the &lt;code&gt;next&lt;/code&gt; pointer of the last node (tail) are typically &lt;code&gt;None&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt; Easier deletion of a given node (without needing its predecessor), and efficient reverse traversal.
&lt;strong&gt;Disadvantages:&lt;/strong&gt; Requires more memory per node (due to the &lt;code&gt;prev&lt;/code&gt; pointer) and slightly more complex insertion/deletion operations.
&lt;strong&gt;Use Cases:&lt;/strong&gt; Implementing LRU caches, browser history (back/forward navigation), and undo/redo functionality in editors.&lt;/p&gt;
&lt;h3 id="3-circular-linked-list"&gt;3. Circular Linked List&lt;/h3&gt;
&lt;p&gt;A circular linked list forms a loop, where the last node points back to an earlier node, often the first node.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;next&lt;/code&gt; pointer of the last node points to the first node (head), forming a circle.&lt;/li&gt;
&lt;li&gt;This means there's no &lt;code&gt;None&lt;/code&gt; pointer to indicate the end of the list.&lt;/li&gt;
&lt;li&gt;Can be singly or doubly circular.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt; Can traverse the entire list starting from any node, useful for continuous cycling applications.
&lt;strong&gt;Disadvantages:&lt;/strong&gt; Care must be taken to avoid infinite loops during traversal if the stopping condition isn't correctly managed.
&lt;strong&gt;Use Cases:&lt;/strong&gt; Round-robin scheduling in operating systems, managing buffers for audio/video streams, or showing items in a carousel.&lt;/p&gt;
&lt;p&gt;For the scope of our deep dive tutorial, we will focus heavily on implementing and understanding singly linked lists, as they form the foundation for the other types.&lt;/p&gt;
&lt;h2 id="implementing-linked-lists-in-python"&gt;Implementing Linked Lists in Python&lt;/h2&gt;
&lt;p&gt;Now that we understand the basic building blocks and types, let's get our hands dirty with a practical implementation of a singly linked list in Python. We'll create a &lt;code&gt;LinkedList&lt;/code&gt; class that manages &lt;code&gt;Node&lt;/code&gt; objects and provides common operations.&lt;/p&gt;
&lt;h3 id="the-linkedlist-class-structure"&gt;The &lt;code&gt;LinkedList&lt;/code&gt; Class Structure&lt;/h3&gt;
&lt;p&gt;Our &lt;code&gt;LinkedList&lt;/code&gt; class will primarily need a &lt;code&gt;head&lt;/code&gt; attribute, which points to the first node in the list. If the list is empty, &lt;code&gt;head&lt;/code&gt; will be &lt;code&gt;None&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LinkedList&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;    A Singly Linked List class.&lt;/span&gt;
&lt;span class="sd"&gt;    Manages nodes and provides operations like append, prepend, delete, etc.&lt;/span&gt;
&lt;span class="sd"&gt;    &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;  &lt;span class="c1"&gt;# The head of the list, initially None for an empty list&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;    &lt;span class="c1"&gt;# To keep track of the number of nodes in the list&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;_size&lt;/code&gt; attribute is a convenience for quickly getting the length of the list without traversing it every time. It must be updated with every insertion and deletion.&lt;/p&gt;
&lt;h3 id="core-operations-and-their-implementations"&gt;Core Operations and Their Implementations&lt;/h3&gt;
&lt;p&gt;Let's break down the essential operations for a singly linked list.&lt;/p&gt;
&lt;h4 id="1-adding-nodes"&gt;1. Adding Nodes&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;a. &lt;code&gt;append(data)&lt;/code&gt;: Add a node to the end of the list.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This is one of the most common ways to add elements.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;new_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_node&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# Traverse to the last node&lt;/span&gt;
                &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_node&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A &lt;code&gt;new_node&lt;/code&gt; is created with the given &lt;code&gt;data&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If the list is empty (&lt;code&gt;self.head is None&lt;/code&gt;), the &lt;code&gt;new_node&lt;/code&gt; becomes the &lt;code&gt;head&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Otherwise, we traverse the list starting from &lt;code&gt;head&lt;/code&gt; until &lt;code&gt;current.next&lt;/code&gt; is &lt;code&gt;None&lt;/code&gt; (meaning &lt;code&gt;current&lt;/code&gt; is the last node).&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;next&lt;/code&gt; pointer of the last node is then updated to point to the &lt;code&gt;new_node&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;_size&lt;/code&gt; is incremented.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;b. &lt;code&gt;prepend(data)&lt;/code&gt;: Add a node to the beginning of the list.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This operation is very efficient.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;prepend&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;new_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;new_node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;  &lt;span class="c1"&gt;# New node points to the current head&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_node&lt;/span&gt;      &lt;span class="c1"&gt;# New node becomes the head&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A &lt;code&gt;new_node&lt;/code&gt; is created.&lt;/li&gt;
&lt;li&gt;Its &lt;code&gt;next&lt;/code&gt; pointer is set to the current &lt;code&gt;head&lt;/code&gt; of the list.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;head&lt;/code&gt; of the list is then updated to be the &lt;code&gt;new_node&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;_size&lt;/code&gt; is incremented.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;c. &lt;code&gt;insert_after(prev_node_data, data)&lt;/code&gt;: Insert a node after a specific node.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This requires finding the predecessor node first.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;insert_after&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;prev_node_data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;List is empty. Cannot insert after a specific node.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;prev_node_data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Node with data &amp;#39;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;prev_node_data&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;#39; not found in the list.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="n"&gt;new_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;new_node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="c1"&gt;# New node points to what current was pointing to&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_node&lt;/span&gt;      &lt;span class="c1"&gt;# Current now points to the new node&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;First, check if the list is empty.&lt;/li&gt;
&lt;li&gt;Traverse the list to find the node (&lt;code&gt;current&lt;/code&gt;) whose data matches &lt;code&gt;prev_node_data&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;prev_node_data&lt;/code&gt; is not found, print an error and return.&lt;/li&gt;
&lt;li&gt;If found, create &lt;code&gt;new_node&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;new_node.next&lt;/code&gt; to &lt;code&gt;current.next&lt;/code&gt; (the node &lt;code&gt;current&lt;/code&gt; was previously pointing to).&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;current.next&lt;/code&gt; to &lt;code&gt;new_node&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;_size&lt;/code&gt; is incremented.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="2-deleting-nodes"&gt;2. Deleting Nodes&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;a. &lt;code&gt;delete_node(key)&lt;/code&gt;: Delete the first node with a given key.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This can involve deleting the head or a node in the middle/end.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;delete_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

        &lt;span class="c1"&gt;# Case 1: Node to be deleted is the head&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="c1"&gt;# Case 2: Node to be deleted is in the middle or end&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;

        &lt;span class="c1"&gt;# Case 3: Key not found&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Node with data &amp;#39;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;#39; not found in the list.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="c1"&gt;# Case 4: Node found, bypass it&lt;/span&gt;
        &lt;span class="n"&gt;prev&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Handles four cases: deleting the head, deleting a middle/end node, or the key not being found.&lt;/li&gt;
&lt;li&gt;If the head needs to be deleted, simply update &lt;code&gt;self.head&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Otherwise, traverse with &lt;code&gt;current&lt;/code&gt; and &lt;code&gt;prev&lt;/code&gt; pointers until &lt;code&gt;current&lt;/code&gt; is the node to delete.&lt;/li&gt;
&lt;li&gt;Once &lt;code&gt;current&lt;/code&gt; is the target, &lt;code&gt;prev.next&lt;/code&gt; is set to &lt;code&gt;current.next&lt;/code&gt;, effectively removing &lt;code&gt;current&lt;/code&gt; from the chain.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;_size&lt;/code&gt; is decremented.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="3-traversing-and-searching"&gt;3. Traversing and Searching&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;a. &lt;code&gt;print_list()&lt;/code&gt;: Traverse and print all nodes.&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;[]&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="n"&gt;nodes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;nodes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot; -&amp;gt; &amp;quot;&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nodes&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Starts from the &lt;code&gt;head&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Iterates through each node, appending its &lt;code&gt;data&lt;/code&gt; to a list.&lt;/li&gt;
&lt;li&gt;Joins the &lt;code&gt;data&lt;/code&gt; with " -&amp;gt; " for a clear representation.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;b. &lt;code&gt;search(key)&lt;/code&gt;: Search for a node with a specific key.&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Traverse the list from &lt;code&gt;head&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;current.data&lt;/code&gt; matches &lt;code&gt;key&lt;/code&gt;, return &lt;code&gt;True&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If the end of the list is reached without finding the key, return &lt;code&gt;False&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="4-utility-operations"&gt;4. Utility Operations&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;a. &lt;code&gt;get_length()&lt;/code&gt;: Get the number of nodes.&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Returns the value of &lt;code&gt;_size&lt;/code&gt;, which is maintained efficiently during other operations.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="putting-it-all-together-a-complete-singly-linked-list-implementation"&gt;Putting It All Together: A Complete Singly Linked List Implementation&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LinkedList&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;new_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_node&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_node&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;prepend&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;new_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;new_node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_node&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;insert_after&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;prev_node_data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;List is empty. Cannot insert after a specific node.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;prev_node_data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Node with data &amp;#39;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;prev_node_data&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;#39; not found in the list.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="n"&gt;new_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;new_node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_node&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;delete_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Node with data &amp;#39;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;#39; not found in the list.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="n"&gt;prev&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;[]&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="n"&gt;nodes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;nodes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot; -&amp;gt; &amp;quot;&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nodes&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt;

&lt;span class="c1"&gt;# Example Usage:&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="vm"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;__main__&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;LinkedList&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Initial list:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Output: []&lt;/span&gt;

    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;After appending 10, 20, 30:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Output: 10 -&amp;gt; 20 -&amp;gt; 30&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Length: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Output: 3&lt;/span&gt;

    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prepend&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;After prepending 5:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Output: 5 -&amp;gt; 10 -&amp;gt; 20 -&amp;gt; 30&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Length: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Output: 4&lt;/span&gt;

    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;insert_after&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;15&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;After inserting 15 after 10:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Output: 5 -&amp;gt; 10 -&amp;gt; 15 -&amp;gt; 20 -&amp;gt; 30&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Length: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Output: 5&lt;/span&gt;

    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;Searching for 20: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Output: True&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Searching for 100: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Output: False&lt;/span&gt;

    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delete_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;After deleting 5 (head):&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Output: 10 -&amp;gt; 15 -&amp;gt; 20 -&amp;gt; 30&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Length: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Output: 4&lt;/span&gt;

    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delete_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;After deleting 20 (middle):&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Output: 10 -&amp;gt; 15 -&amp;gt; 30&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Length: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Output: 3&lt;/span&gt;

    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delete_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;After deleting 30 (tail):&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Output: 10 -&amp;gt; 15&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Length: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Output: 2&lt;/span&gt;

    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delete_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Output: Node with data &amp;#39;100&amp;#39; not found in the list.&lt;/span&gt;
    &lt;span class="n"&gt;my_list&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;print_list&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Output: 10 -&amp;gt; 15&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h2 id="time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the performance characteristics of linked list operations is crucial for choosing the right data structure. For a more comprehensive understanding of these concepts, refer to our guide on &lt;a href="/big-o-notation-explained-beginner-guide-complexity/"&gt;Big O Notation Explained: A Beginner's Guide to Complexity&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Operation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Access/Search (by value):&lt;/strong&gt; O(n)&lt;ul&gt;
&lt;li&gt;To find an element, you might have to traverse the entire list from the head, as there's no direct indexing.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Access (by index):&lt;/strong&gt; O(n)&lt;ul&gt;
&lt;li&gt;Similar to searching by value, you must traverse &lt;code&gt;k&lt;/code&gt; nodes to reach the &lt;code&gt;k&lt;/code&gt;-th element.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Insertion/Deletion at Head:&lt;/strong&gt; O(1)&lt;ul&gt;
&lt;li&gt;Simply update the &lt;code&gt;head&lt;/code&gt; pointer.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Insertion/Deletion at Tail:&lt;/strong&gt; O(n)&lt;ul&gt;
&lt;li&gt;Requires traversing the entire list to find the last node.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Insertion/Deletion at Middle:&lt;/strong&gt; O(n)&lt;ul&gt;
&lt;li&gt;Requires traversing to the node &lt;em&gt;before&lt;/em&gt; the insertion/deletion point.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Summary Table:&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style="text-align: left;"&gt;Operation&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Time Complexity (Singly Linked List)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Access (by index)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Search (by value)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Prepend&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(1)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Append&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Insert After&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Delete Head&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(1)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;Delete Middle/Tail&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Overall Space:&lt;/strong&gt; O(n)&lt;ul&gt;
&lt;li&gt;A linked list requires space proportional to the number of nodes (n). Each node stores its data and a pointer.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Auxiliary Space (for most operations):&lt;/strong&gt; O(1)&lt;ul&gt;
&lt;li&gt;Most operations like insertion, deletion, or traversal only require a few extra pointers (&lt;code&gt;current&lt;/code&gt;, &lt;code&gt;prev&lt;/code&gt;, &lt;code&gt;new_node&lt;/code&gt;), making their auxiliary space complexity constant.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="linked-list-vs-array-when-to-use-which"&gt;Linked List vs. Array: When to Use Which?&lt;/h2&gt;
&lt;p&gt;The choice between a linked list and an array (or Python's built-in &lt;code&gt;list&lt;/code&gt; which is a dynamic array) often comes down to the specific use case and the frequency of certain operations.&lt;/p&gt;
&lt;h3 id="key-differences"&gt;Key Differences&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Memory Allocation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Arrays:&lt;/strong&gt; Store elements in contiguous memory locations. This allows for direct indexing (O(1) access). However, resizing can be expensive (creating a new, larger array and copying elements).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Linked Lists:&lt;/strong&gt; Store elements non-contiguously. Each node has its own memory location and points to the next. This makes insertion and deletion efficient in many cases but sacrifices direct access.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Access Time:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Arrays:&lt;/strong&gt; O(1) for random access (e.g., &lt;code&gt;arr[5]&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Linked Lists:&lt;/strong&gt; O(n) for random access; you must traverse from the head.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion/Deletion:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Arrays:&lt;/strong&gt; O(n) in the worst case (e.g., inserting at the beginning requires shifting all subsequent elements). Amortized O(1) for appending if capacity allows, O(n) if reallocation is needed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Linked Lists:&lt;/strong&gt; O(1) for insertion/deletion at the head (or tail for doubly linked lists). O(n) for insertion/deletion in the middle or at the tail (for singly linked lists) because you first need to find the specific position.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Memory Usage:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Arrays:&lt;/strong&gt; Generally more memory-efficient &lt;em&gt;per element&lt;/em&gt; as they only store data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Linked Lists:&lt;/strong&gt; More memory-intensive &lt;em&gt;per element&lt;/em&gt; because each node stores both data and at least one pointer.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="when-to-use-a-linked-list"&gt;When to Use a Linked List&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Frequent insertions/deletions at unknown positions:&lt;/strong&gt; If you frequently add or remove elements, especially from the beginning or middle, and the exact position isn't always known upfront, linked lists excel.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dynamic size requirements:&lt;/strong&gt; When the number of elements is highly variable and changes frequently, linked lists are ideal as they don't require pre-allocation or costly reallocations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Implementing other data structures:&lt;/strong&gt; They form the basis for queues, stacks, and hash tables with chaining.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No random access needed:&lt;/strong&gt; If you primarily process elements sequentially (e.g., iterating through all items), the lack of random access isn't a significant drawback.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="when-to-use-an-array-python-list"&gt;When to Use an Array (Python List)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Frequent random access by index:&lt;/strong&gt; If you often need to access elements at specific positions (&lt;code&gt;list[i]&lt;/code&gt;), arrays are significantly faster.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fixed or predictable size:&lt;/strong&gt; If the number of elements is known beforehand or changes infrequently.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Iterating through elements:&lt;/strong&gt; While linked lists can be iterated, arrays often have better cache performance due to contiguous memory.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory efficiency is critical:&lt;/strong&gt; If you need to store a large number of simple items and pointer overhead is a concern.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Python's built-in &lt;code&gt;list&lt;/code&gt; is a highly optimized dynamic array. For most general-purpose applications in Python, the &lt;code&gt;list&lt;/code&gt; type is usually preferred due to its C-level optimizations and flexibility. However, understanding and implementing linked lists is crucial for specific algorithmic problems, deeper computer science understanding, and environments where Python's &lt;code&gt;list&lt;/code&gt; might not perfectly fit the performance profile (e.g., memory-constrained systems or languages like C/C++).&lt;/p&gt;
&lt;h2 id="real-world-applications-of-linked-lists"&gt;Real-World Applications of Linked Lists&lt;/h2&gt;
&lt;p&gt;Linked lists aren't just theoretical constructs; they underpin many practical systems and algorithms.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Implementing Stacks and Queues:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Stacks (LIFO):&lt;/strong&gt; Can be efficiently implemented using a singly linked list where &lt;code&gt;push&lt;/code&gt; (add to top) and &lt;code&gt;pop&lt;/code&gt; (remove from top) operations correspond to &lt;code&gt;prepend&lt;/code&gt; and &lt;code&gt;delete_head&lt;/code&gt; operations, respectively, both taking O(1) time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Queues (FIFO):&lt;/strong&gt; Can be implemented with a singly linked list by maintaining both &lt;code&gt;head&lt;/code&gt; and &lt;code&gt;tail&lt;/code&gt; pointers. &lt;code&gt;enqueue&lt;/code&gt; (add to rear) maps to &lt;code&gt;append&lt;/code&gt; (O(1) with tail pointer) and &lt;code&gt;dequeue&lt;/code&gt; (remove from front) maps to &lt;code&gt;delete_head&lt;/code&gt; (O(1)).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Image Viewers and Music Playlists:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Applications that allow "next" and "previous" functionality (like an image gallery or a music player) often use doubly linked lists. Each image/song is a node, and the &lt;code&gt;next&lt;/code&gt; and &lt;code&gt;prev&lt;/code&gt; pointers allow seamless navigation.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Browser History (Forward/Backward Navigation):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Similar to media players, web browsers can use doubly linked lists to manage your browsing history. Each webpage visited is a node, and the &lt;code&gt;prev&lt;/code&gt; and &lt;code&gt;next&lt;/code&gt; pointers enable navigating back and forth through your session.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Memory Management (Free List):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Operating systems and memory allocators sometimes use linked lists to keep track of available (free) memory blocks. When a process requests memory, a suitable block is found and removed from the list. When memory is freed, it's added back to the list.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Undo/Redo Functionality:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In text editors or graphic design software, the history of actions for undo/redo features can be managed by a doubly linked list. Each action (typing, drawing a shape) is a node.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Hash Tables (Collision Resolution):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;When multiple keys map to the same index in a hash table (a "collision"), linked lists are commonly used to store these colliding keys at that index. This technique is called "separate chaining." For a deep dive into this, check out our article on &lt;a href="/hash-tables-deep-dive-how-they-work-use-cases/"&gt;Hash Tables: Deep Dive into Their Inner Workings &amp;amp; Use Cases&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Polynomial Representation:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Polynomials like &lt;code&gt;3x^2 + 2x + 5&lt;/code&gt; can be represented using a linked list, where each node stores a term's coefficient and exponent.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Graph Representation (Adjacency List):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Linked lists are a fundamental component in representing graphs, especially sparse graphs. An adjacency list uses an array of linked lists, where each array index represents a vertex, and its linked list contains all vertices adjacent to it.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These examples demonstrate the versatility and fundamental role linked lists play in software development, often behind the scenes, providing efficient solutions for dynamic data management.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="common-linked-list-interview-questions-and-patterns"&gt;Common Linked List Interview Questions and Patterns&lt;/h2&gt;
&lt;p&gt;Linked lists are a staple in coding interviews, primarily because they test a candidate's understanding of pointers, edge cases, and algorithmic thinking without relying on complex data structures. Mastering these patterns is crucial for any tech professional.&lt;/p&gt;
&lt;h3 id="1-reversing-a-linked-list"&gt;1. Reversing a Linked List&lt;/h3&gt;
&lt;p&gt;This is perhaps the most famous linked list problem. You're given the head of a singly linked list and need to reverse it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pattern:&lt;/strong&gt; Requires three pointers (&lt;code&gt;prev&lt;/code&gt;, &lt;code&gt;current&lt;/code&gt;, &lt;code&gt;next_node&lt;/code&gt;) to keep track of the node being processed, its predecessor, and its successor, allowing you to re-link nodes correctly.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Assuming Node class is defined&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;reverse_linked_list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
    &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;next_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="c1"&gt;# Store next node&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;prev&lt;/span&gt;      &lt;span class="c1"&gt;# Reverse current node&amp;#39;s pointer&lt;/span&gt;
        &lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;           &lt;span class="c1"&gt;# Move prev to current node&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;next_node&lt;/span&gt;      &lt;span class="c1"&gt;# Move current to next node&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="c1"&gt;# prev will be the new head&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="2-detecting-a-cycle-floyds-cycle-finding-algorithm"&gt;2. Detecting a Cycle (Floyd's Cycle-Finding Algorithm)&lt;/h3&gt;
&lt;p&gt;Given the head of a linked list, determine if it has a cycle. A cycle exists if any node in the list points to an earlier node, forming a loop.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pattern:&lt;/strong&gt; Use two pointers, a "slow" pointer (moves one step at a time) and a "fast" pointer (moves two steps at a time). If there's a cycle, the fast pointer will eventually catch up to the slow pointer.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;has_cycle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;slow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;
    &lt;span class="n"&gt;fast&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;fast&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;fast&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;slow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;slow&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="n"&gt;fast&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;fast&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;slow&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;fast&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt; &lt;span class="c1"&gt;# Cycle detected&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt; &lt;span class="c1"&gt;# No cycle&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="3-finding-the-middle-of-a-linked-list"&gt;3. Finding the Middle of a Linked List&lt;/h3&gt;
&lt;p&gt;Return the middle node of the linked list. If the list has an even number of nodes, return the second middle node.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pattern:&lt;/strong&gt; Again, use two pointers, slow and fast. The fast pointer moves twice as fast as the slow pointer. When the fast pointer reaches the end, the slow pointer will be at the middle.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find_middle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;slow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;
    &lt;span class="n"&gt;fast&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;head&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;fast&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;fast&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;slow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;slow&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="n"&gt;fast&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;fast&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;slow&lt;/span&gt; &lt;span class="c1"&gt;# Slow pointer is at the middle&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="4-merging-two-sorted-linked-lists"&gt;4. Merging Two Sorted Linked Lists&lt;/h3&gt;
&lt;p&gt;Given the heads of two sorted linked lists, merge them into a single sorted linked list and return the head of the merged list.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pattern:&lt;/strong&gt; Use a dummy node to simplify the logic, and iteratively compare the current nodes of both lists, appending the smaller one to the merged list.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;merge_two_lists&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;l1_head&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;l2_head&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;dummy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Dummy node to simplify edge cases&lt;/span&gt;
    &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dummy&lt;/span&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;l1_head&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;l2_head&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;l1_head&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;l2_head&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l1_head&lt;/span&gt;
            &lt;span class="n"&gt;l1_head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l1_head&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l2_head&lt;/span&gt;
            &lt;span class="n"&gt;l2_head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l2_head&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;

    &lt;span class="c1"&gt;# Attach remaining nodes if any&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;l1_head&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l1_head&lt;/span&gt;
    &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;l2_head&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l2_head&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dummy&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="c1"&gt;# The actual head of the merged list&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;These patterns are fundamental to solving a wide array of linked list problems and demonstrate a deep understanding of pointer manipulation.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="advanced-concepts-and-optimizations"&gt;Advanced Concepts and Optimizations&lt;/h2&gt;
&lt;p&gt;While the basic linked list is powerful, there are several advanced concepts and optimizations that can be applied depending on the requirements.&lt;/p&gt;
&lt;h3 id="sentinel-dummy-nodes"&gt;Sentinel (Dummy) Nodes&lt;/h3&gt;
&lt;p&gt;A common optimization, particularly in competitive programming, is the use of a "sentinel" or "dummy" node. This is an extra node at the beginning of the linked list that does not hold actual data but simplifies code by providing a consistent starting point.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Simplifies edge cases:&lt;/strong&gt; Operations like inserting at the head or deleting the head become identical to inserting/deleting in the middle, as the actual head always has a predecessor (the dummy node).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reduces &lt;code&gt;if self.head is None&lt;/code&gt; checks:&lt;/strong&gt; Code becomes cleaner and less prone to errors due to fewer special checks for an empty list.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Implementation:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LinkedListWithDummy&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Sentinel node, its data doesn&amp;#39;t matter&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Always traverse from self.head (the dummy) to find the end&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_size&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Notice how &lt;code&gt;append&lt;/code&gt; now always starts from the dummy node, making the logic slightly more uniform. The actual list starts from &lt;code&gt;self.head.next&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="skip-lists"&gt;Skip Lists&lt;/h3&gt;
&lt;p&gt;For very large datasets where search performance is crucial, but maintaining a balanced tree structure is too complex or costly, skip lists offer an alternative. A skip list is a probabilistic data structure that allows O(log n) average time complexity for search, insertion, and deletion operations. While discussing balanced binary search trees (like AVL or Red-Black trees), which offer similar performance, you might find our guide on &lt;a href="/binary-search-tree-step-by-step-implementation-guide/"&gt;Binary Search Tree: A Step-by-Step Implementation Guide for Developers&lt;/a&gt; helpful for understanding tree-based data structures.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt; It's essentially multiple linked lists stacked on top of each other. Each list is a "express lane" version of the one below it, containing a subset of the nodes. Nodes randomly decide to be part of higher-level lists, creating "shortcuts" that allow for faster traversal.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Benefits:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Probabilistic O(log n) performance for most operations.&lt;/li&gt;
&lt;li&gt;Simpler to implement than balanced binary search trees (like AVL or Red-Black trees).&lt;/li&gt;
&lt;li&gt;Excellent for concurrent access, as individual nodes can be locked without locking the entire structure.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Drawbacks:&lt;/strong&gt; More complex to implement than a standard linked list, and worst-case performance can degrade to O(n) (though highly improbable).&lt;/p&gt;
&lt;h3 id="memory-pool-allocation"&gt;Memory Pool Allocation&lt;/h3&gt;
&lt;p&gt;In performance-critical applications, especially in languages like C/C++, dynamically allocating individual nodes can lead to fragmentation and overhead. A memory pool pre-allocates a large block of memory and manages nodes within that block.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt; Instead of calling &lt;code&gt;new Node()&lt;/code&gt; for each node, you allocate nodes from a custom-managed contiguous block. When a node is "deleted," it's not truly freed to the OS but marked as available in the pool.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Benefits:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Reduced fragmentation:&lt;/strong&gt; Keeps linked list nodes closer in memory, potentially improving cache performance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Faster allocation/deallocation:&lt;/strong&gt; Custom allocation can be significantly faster than general-purpose memory allocators.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Predictable performance:&lt;/strong&gt; Avoids performance spikes associated with OS-level memory management.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;While Python's garbage collector handles memory management automatically, understanding memory pools is valuable for systems programming and highly optimized custom data structures.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="pros-and-cons-of-linked-lists"&gt;Pros and Cons of Linked Lists&lt;/h2&gt;
&lt;p&gt;Like any data structure, linked lists come with their own set of advantages and disadvantages. Choosing whether to use one depends heavily on the specific requirements of the problem.&lt;/p&gt;
&lt;h3 id="advantages-pros"&gt;Advantages (Pros)&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Dynamic Size:&lt;/strong&gt; Linked lists can grow or shrink in size during runtime without being restricted by an initial declaration. They can allocate memory for new nodes as needed. This flexibility is a major advantage over static arrays.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficient Insertions and Deletions (at certain positions):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Adding or removing a node at the beginning of a singly linked list takes O(1) time.&lt;/li&gt;
&lt;li&gt;Adding or removing a node at any arbitrary position (once that position is found) also takes O(1) time. This is because you only need to update a few pointers, unlike arrays where shifting elements takes O(n) time.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No Memory Waste (No Pre-allocation):&lt;/strong&gt; Unlike arrays which might pre-allocate more memory than needed to avoid frequent resizing (leading to wasted space), linked lists only allocate memory for the nodes they currently hold.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Flexible Data Types:&lt;/strong&gt; Each node can store any type of data, including custom objects, similar to Python's dynamic typing capabilities.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="disadvantages-cons"&gt;Disadvantages (Cons)&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;No Random Access:&lt;/strong&gt; To access an element at a specific index (e.g., the 5th element), you must traverse the list from the beginning (head) until you reach that element. This makes random access an O(n) operation, a significant drawback compared to arrays' O(1) access.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;More Memory Usage:&lt;/strong&gt; Each node in a linked list requires extra memory to store one or more pointers to other nodes. This overhead (data + pointer) means that a linked list generally uses more memory than an array for the same number of data elements.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cache Performance:&lt;/strong&gt; Because linked list nodes are not stored contiguously in memory, accessing successive nodes often results in cache misses. Modern CPUs perform much better with contiguous memory blocks (like arrays) due to cache locality.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Harder to Traverse Backwards (for Singly Linked Lists):&lt;/strong&gt; Traversing a singly linked list backwards is impossible without either reversing the list or using a stack to store nodes, both of which introduce additional overhead. Doubly linked lists solve this but add more memory overhead per node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Complexity:&lt;/strong&gt; While basic operations are simple, managing pointers, especially in more complex scenarios or with doubly/circular linked lists, can be more error-prone than array manipulations. Debugging pointer issues can be challenging.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id="future-outlook-and-modern-relevance"&gt;Future Outlook and Modern Relevance&lt;/h2&gt;
&lt;p&gt;While linked lists might seem like a traditional data structure, their fundamental principles remain highly relevant in modern computing, particularly as systems grow more distributed and memory management becomes more nuanced.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Continued Relevance in Core Systems:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Linked lists continue to be integral to operating system kernels, embedded systems, and low-level programming where explicit memory control is paramount. Custom memory allocators, device drivers, and real-time systems often leverage linked lists for their predictable O(1) insertion/deletion properties at specific points.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Underlying Complex Data Structures:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Many advanced data structures like hash maps (using separate chaining for collision resolution), adjacency lists for graph representations, and even some custom tree implementations still rely on linked lists at their core. Understanding linked lists is thus a gateway to comprehending these more complex structures.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Educational and Interview Value:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;As established, linked lists are indispensable in computer science education and technical interviews. They serve as a perfect medium to evaluate a candidate's grasp of pointers, recursion, edge cases, and algorithmic problem-solving. This makes them eternally relevant for career progression in tech.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Emergence of Functional Programming:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In functional programming paradigms, immutable linked lists (where operations return a new list rather than modifying the original) are common. While Python itself isn't purely functional, understanding immutable data structures (often backed by linked lists) is valuable for paradigms like persistent data structures, which have applications in databases and version control systems.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Python's Ecosystem:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Although Python's built-in &lt;code&gt;list&lt;/code&gt; (dynamic array) is usually the go-to for general sequential data, explicit linked list implementations appear in libraries or frameworks where their specific performance characteristics (e.g., constant-time prepend/deletion from the start) are critical, and the overhead of Python objects is accepted. For instance, in &lt;code&gt;collections.deque&lt;/code&gt;, while not a true linked list, it offers O(1) appends and pops from both ends, achieving similar performance profiles for queues.&lt;/p&gt;
&lt;p&gt;In conclusion, while direct use of custom linked lists in high-level Python application code might be less frequent due to the powerful built-in &lt;code&gt;list&lt;/code&gt; and &lt;code&gt;deque&lt;/code&gt; types, their conceptual importance and foundational role in computer science, system design, and algorithmic thinking ensure that &lt;strong&gt;Linked Lists in Python: A Deep Dive Tutorial&lt;/strong&gt; remains a timeless and essential topic for any serious technologist.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: Why choose linked lists over Python lists (arrays)?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Linked lists offer efficient O(1) insertions and deletions at the head and flexible dynamic sizing, making them ideal when data changes frequently. Python lists (arrays) provide O(1) random access but can be O(n) for insertions/deletions in the middle due to element shifting.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What are the main types of linked lists?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The three main types are singly linked lists (nodes point only forward), doubly linked lists (nodes point both forward and backward), and circular linked lists (the last node points back to an earlier node, often the head). Each type has distinct advantages and use cases.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Where are linked lists used in real-world applications?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Linked lists are fundamental in implementing other data structures like stacks and queues, managing browser history, representing polynomial expressions, and resolving collisions in hash tables (separate chaining). They also play roles in operating system memory management.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/data-structures-linked-list/"&gt;GeeksforGeeks: Linked List Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.programiz.com/dsa/linked-list"&gt;Programiz: Python Linked List&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://realpython.com/linked-lists-python/"&gt;Real Python: Python Linked Lists&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/tag/linked-list/"&gt;LeetCode Linked List Problems&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Linked_list"&gt;Wikipedia: Linked List&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="LeetCode"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/linked-lists-python-deep-dive-tutorial-data-structures.webp" width="1200"/><media:title type="plain">Linked Lists in Python: A Deep Dive Tutorial into Data Structures</media:title><media:description type="plain">Explore Linked Lists in Python: A Deep Dive Tutorial covering fundamental concepts, implementations, complexity analysis, and real-world applications for tec...</media:description></entry><entry><title>Hash Tables: Comprehensive Guide &amp; Real-World Uses</title><link href="https://analyticsdrive.tech/hash-tables-comprehensive-guide-real-world-uses/" rel="alternate"/><published>2026-03-21T22:19:00+05:30</published><updated>2026-03-21T22:19:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-21:/hash-tables-comprehensive-guide-real-world-uses/</id><summary type="html">&lt;p&gt;Dive deep into Hash Tables: Comprehensive Guide &amp;amp; Real-World Uses. Explore their mechanics, collision resolution, performance, and essential applications in ...&lt;/p&gt;</summary><content type="html">&lt;p&gt;In the vast and intricate landscape of computer science, efficient data management is paramount. Among the most fundamental and versatile data structures, &lt;strong&gt;Hash Tables: Comprehensive Guide &amp;amp; Real-World Uses&lt;/strong&gt; stand out as indispensable tools for achieving lightning-fast data retrieval and storage. This deep dive will explore their core mechanics, unveil the sophisticated algorithms behind their efficiency, and illuminate the countless real-world applications that power much of our digital infrastructure, offering a truly comprehensive understanding for the tech-savvy reader.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-are-hash-tables"&gt;What Are Hash Tables?&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-core-concept-key-value-pairs"&gt;The Core Concept: Key-Value Pairs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#analogy-the-digital-library"&gt;Analogy: The Digital Library&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#how-hash-tables-work-the-underlying-mechanism"&gt;How Hash Tables Work: The Underlying Mechanism&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#hash-function-the-engine"&gt;Hash Function: The Engine&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#collision-resolution-handling-the-inevitable"&gt;Collision Resolution: Handling the Inevitable&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#chaining-linked-lists"&gt;Chaining: Linked Lists&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#open-addressing-probing-strategies"&gt;Open Addressing: Probing Strategies&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#linear-probing"&gt;Linear Probing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#quadratic-probing"&gt;Quadratic Probing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#double-hashing"&gt;Double Hashing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#performance-characteristics-and-big-o-notation"&gt;Performance Characteristics and Big O Notation&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#average-case-performance"&gt;Average Case Performance&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#worst-case-performance"&gt;Worst Case Performance&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#load-factor-balancing-efficiency"&gt;Load Factor: Balancing Efficiency&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-implementations-and-data-structures"&gt;Common Implementations and Data Structures&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#pythons-dictionaries"&gt;Python's Dictionaries&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#javas-hashmap"&gt;Java's HashMap&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#cs-stdunordered_map"&gt;C++'s std::unordered_map&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-uses-of-hash-tables-practical-applications"&gt;Real-World Uses of Hash Tables: Practical Applications&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#database-indexing"&gt;Database Indexing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#caching-systems"&gt;Caching Systems&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#symbol-tables-in-compilers"&gt;Symbol Tables in Compilers&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#unique-data-identification"&gt;Unique Data Identification&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#network-routers-and-firewalls"&gt;Network Routers and Firewalls&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#cryptography-and-data-integrity"&gt;Cryptography and Data Integrity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#advantages-and-disadvantages-of-hash-tables"&gt;Advantages and Disadvantages of Hash Tables&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#key-advantages"&gt;Key Advantages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#potential-disadvantages"&gt;Potential Disadvantages&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#advanced-concepts-and-future-outlook"&gt;Advanced Concepts and Future Outlook&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#perfect-hashing"&gt;Perfect Hashing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#cuckoo-hashing"&gt;Cuckoo Hashing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#distributed-hash-tables-dhts"&gt;Distributed Hash Tables (DHTs)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#quantum-computing-and-hashing"&gt;Quantum Computing and Hashing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="what-are-hash-tables"&gt;What Are Hash Tables?&lt;/h2&gt;
&lt;p&gt;At its heart, a hash table, also known as a hash map, is a data structure that implements an associative array abstract data type. This means it stores key-value pairs, allowing you to quickly look up a value given its key. Think of it as a highly optimized dictionary where each word (key) has a specific definition (value), and you can find any word's definition almost instantaneously, regardless of how many words are in the dictionary.&lt;/p&gt;
&lt;p&gt;The primary goal of a hash table is to provide average-case O(1) (constant time) complexity for insertion, deletion, and retrieval operations. This extraordinary efficiency makes them a cornerstone of modern computing, enabling performance in scenarios where other data structures might falter under heavy loads. Unlike arrays, which use numerical indices, or linked lists, which require sequential traversal, hash tables use a special function to compute an index directly from the key.&lt;/p&gt;
&lt;h3 id="the-core-concept-key-value-pairs"&gt;The Core Concept: Key-Value Pairs&lt;/h3&gt;
&lt;p&gt;The foundational element of a hash table is the key-value pair. Every piece of data stored in a hash table consists of two parts:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Key:&lt;/strong&gt; A unique identifier that you use to look up the data. This could be a string (like a username), a number (like an ID), or even an object. Keys must be hashable, meaning they can be consistently converted into a numerical hash code.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Value:&lt;/strong&gt; The actual data associated with the key. This can be any type of data, from a simple integer to a complex object.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When you want to store something, you provide both a key and a value. When you want to retrieve something, you only need to provide the key, and the hash table will efficiently locate and return the corresponding value. This direct mapping from key to value is what gives hash tables their power.&lt;/p&gt;
&lt;h3 id="analogy-the-digital-library"&gt;Analogy: The Digital Library&lt;/h3&gt;
&lt;p&gt;Imagine a massive digital library where instead of finding books by their alphabetical title, you could magically know the exact shelf and position of any book just by knowing its title.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The Librarian (Hash Function):&lt;/strong&gt; When a new book (key-value pair) arrives, the librarian (hash function) takes the book's title (key) and instantly calculates a specific shelf number and slot (index). This calculation is deterministic; the same title always produces the same location.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Shelves (Array/Buckets):&lt;/strong&gt; The library has a fixed number of shelves (an underlying array or set of "buckets"). Each shelf can hold multiple books.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Storing a Book:&lt;/strong&gt; The librarian places the book at the calculated shelf and slot.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Retrieving a Book:&lt;/strong&gt; When you ask for a book by its title, the librarian applies the same calculation to get the exact shelf and slot, and retrieves the book almost instantly.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This system works wonderfully, but what happens if two different book titles (keys) magically get assigned to the same shelf and slot by the librarian? This is a "collision," and handling it effectively is crucial to the hash table's performance and correctness.&lt;/p&gt;
&lt;h2 id="how-hash-tables-work-the-underlying-mechanism"&gt;How Hash Tables Work: The Underlying Mechanism&lt;/h2&gt;
&lt;p&gt;The efficiency of hash tables hinges on two core components: the hash function and the collision resolution strategy. Understanding how these work in tandem is key to grasping the power and intricacies of this data structure.&lt;/p&gt;
&lt;h3 id="hash-function-the-engine"&gt;Hash Function: The Engine&lt;/h3&gt;
&lt;p&gt;A hash function is the magical "librarian" that takes an input key and transforms it into an integer, called a hash code or hash value. This hash code is then typically mapped to an index within the hash table's underlying array (often by using the modulo operator).&lt;/p&gt;
&lt;p&gt;Key properties of a good hash function:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Determinism:&lt;/strong&gt; The same key must always produce the same hash value. Without this, retrieval would be impossible.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficiency:&lt;/strong&gt; It must compute the hash value quickly, as this operation is performed for every insertion, deletion, and lookup.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Uniform Distribution:&lt;/strong&gt; It should distribute keys as evenly as possible across the entire range of possible hash values. A poor distribution leads to more collisions, degrading performance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sensitivity:&lt;/strong&gt; Even a small change in the input key should result in a significantly different hash value. This helps in avoiding clusters of hash values.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let's consider a simple example. If we have keys that are integers, a basic hash function might be &lt;code&gt;h(key) = key % N&lt;/code&gt;, where &lt;code&gt;N&lt;/code&gt; is the size of the array (number of buckets). For string keys, the process is more complex, often involving summing ASCII values or polynomial rolling hashes, but the goal remains the same: convert the key into an integer index.&lt;/p&gt;
&lt;h3 id="collision-resolution-handling-the-inevitable"&gt;Collision Resolution: Handling the Inevitable&lt;/h3&gt;
&lt;p&gt;No matter how good a hash function is, collisions are bound to happen, especially as the number of keys increases. A collision occurs when two different keys hash to the same index in the array. If not handled properly, a collision would mean one key overwrites another or makes it unreachable. There are two primary strategies for resolving these collisions: chaining and open addressing.&lt;/p&gt;
&lt;h4 id="chaining-linked-lists"&gt;Chaining: Linked Lists&lt;/h4&gt;
&lt;p&gt;Chaining is one of the most straightforward and widely used collision resolution techniques. When multiple keys hash to the same index, instead of overwriting, all key-value pairs that hash to that index are stored in a linked list at that array position.&lt;/p&gt;
&lt;p&gt;How it works:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Each slot in the hash table's underlying array is a "bucket."&lt;/li&gt;
&lt;li&gt;If a key hashes to an index where another key already exists, the new key-value pair is simply added to the linked list at that bucket.&lt;/li&gt;
&lt;li&gt;For retrieval, the hash function directs to the correct bucket, and then the linked list is traversed until the desired key is found.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Advantages:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Relatively simple to implement.&lt;/li&gt;
&lt;li&gt;The hash table never "fills up" (as long as there's memory for linked lists).&lt;/li&gt;
&lt;li&gt;Less sensitive to the load factor compared to open addressing.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Disadvantages:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Requires additional memory for pointers in the linked lists.&lt;/li&gt;
&lt;li&gt;Can degrade to O(N) performance in the worst case if all keys hash to the same bucket, turning the linked list into a single long list.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="open-addressing-probing-strategies"&gt;Open Addressing: Probing Strategies&lt;/h4&gt;
&lt;p&gt;Open addressing attempts to find another open slot (probe) in the array itself if the initial hash location is occupied. Instead of external data structures like linked lists, all elements are stored directly within the hash table's array.&lt;/p&gt;
&lt;p&gt;How it works:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;When a collision occurs, the system probes for an alternative empty slot within the array using a predefined sequence.&lt;/li&gt;
&lt;li&gt;During retrieval, if the key is not found at its initial hash location, the system follows the same probing sequence until it finds the key or an empty slot (indicating the key is not present).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;There are several probing strategies:&lt;/p&gt;
&lt;h5 id="linear-probing"&gt;Linear Probing&lt;/h5&gt;
&lt;p&gt;In linear probing, if a slot &lt;code&gt;h(key)&lt;/code&gt; is occupied, the algorithm checks &lt;code&gt;h(key) + 1&lt;/code&gt;, then &lt;code&gt;h(key) + 2&lt;/code&gt;, and so on (modulo array size), until an empty slot is found.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Hash table size &lt;code&gt;N=10&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Keys: &lt;code&gt;10, 20, 30&lt;/code&gt;. All hash to index &lt;code&gt;0&lt;/code&gt; if &lt;code&gt;h(key) = key % 10&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;10&lt;/code&gt; goes to index &lt;code&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;20&lt;/code&gt; hashes to &lt;code&gt;0&lt;/code&gt;, but &lt;code&gt;0&lt;/code&gt; is occupied by &lt;code&gt;10&lt;/code&gt;. So, &lt;code&gt;20&lt;/code&gt; goes to &lt;code&gt;0+1 = 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;30&lt;/code&gt; hashes to &lt;code&gt;0&lt;/code&gt;, &lt;code&gt;0&lt;/code&gt; is occupied, &lt;code&gt;1&lt;/code&gt; is occupied. So, &lt;code&gt;30&lt;/code&gt; goes to &lt;code&gt;1+1 = 2&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Problem:
This can lead to "primary clustering," where long runs of occupied slots form, making future insertions and searches take longer as the probe sequence becomes extended.&lt;/p&gt;
&lt;h5 id="quadratic-probing"&gt;Quadratic Probing&lt;/h5&gt;
&lt;p&gt;To mitigate primary clustering, quadratic probing uses a quadratic sequence for probing. If &lt;code&gt;h(key)&lt;/code&gt; is occupied, it checks &lt;code&gt;h(key) + 1^2&lt;/code&gt;, then &lt;code&gt;h(key) + 2^2&lt;/code&gt;, then &lt;code&gt;h(key) + 3^2&lt;/code&gt;, and so on (modulo array size).&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Hash table size &lt;code&gt;N=10&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Key &lt;code&gt;K1&lt;/code&gt; hashes to index &lt;code&gt;5&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Key &lt;code&gt;K2&lt;/code&gt; hashes to index &lt;code&gt;5&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;K1&lt;/code&gt; goes to index &lt;code&gt;5&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;K2&lt;/code&gt; hashes to &lt;code&gt;5&lt;/code&gt;, but &lt;code&gt;5&lt;/code&gt; is occupied. So, &lt;code&gt;K2&lt;/code&gt; checks &lt;code&gt;5 + 1^2 = 6&lt;/code&gt;. If &lt;code&gt;6&lt;/code&gt; is occupied, it checks &lt;code&gt;5 + 2^2 = 9&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Problem:
Can lead to "secondary clustering," where keys that hash to the same initial location follow the same probing sequence, even if that sequence isn't a long block.&lt;/p&gt;
&lt;h5 id="double-hashing"&gt;Double Hashing&lt;/h5&gt;
&lt;p&gt;Double hashing uses a second hash function &lt;code&gt;h2(key)&lt;/code&gt; to determine the step size for probing. If &lt;code&gt;h(key)&lt;/code&gt; is occupied, the probe sequence is &lt;code&gt;h(key) + 1*h2(key)&lt;/code&gt;, then &lt;code&gt;h(key) + 2*h2(key)&lt;/code&gt;, then &lt;code&gt;h(key) + 3*h2(key)&lt;/code&gt;, etc. (modulo array size). The second hash function &lt;code&gt;h2(key)&lt;/code&gt; must never return zero and should be relatively prime to the table size &lt;code&gt;N&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Hash table size &lt;code&gt;N=10&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;h(key) = key % 10&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;h2(key) = 7 - (key % 7)&lt;/code&gt; (a common choice for &lt;code&gt;h2(key)&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Key &lt;code&gt;10&lt;/code&gt; hashes &lt;code&gt;h(10) = 0&lt;/code&gt;. &lt;code&gt;h2(10) = 7 - (10 % 7) = 7 - 3 = 4&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;0&lt;/code&gt; is occupied, the next probe is &lt;code&gt;0 + 4 = 4&lt;/code&gt;. Then &lt;code&gt;0 + 2*4 = 8&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Advantages:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Significantly reduces both primary and secondary clustering by generating a unique probing sequence for each key, effectively spreading out collisions.&lt;/li&gt;
&lt;li&gt;Offers excellent performance characteristics in practice.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="performance-characteristics-and-big-o-notation"&gt;Performance Characteristics and &lt;a href="https://analyticsdrive.tech/big-o-notation/"&gt;Big O Notation&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;The appeal of hash tables lies in their exceptional average-case performance. Understanding their complexity using &lt;a href="/big-o-notation-explained-beginner-guide-complexity/"&gt;Big O notation&lt;/a&gt; is crucial for tech professionals.&lt;/p&gt;
&lt;h3 id="average-case-performance"&gt;Average Case Performance&lt;/h3&gt;
&lt;p&gt;Under ideal conditions (a good hash function and proper load factor management), hash tables offer:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Insertion (Put):&lt;/strong&gt; O(1)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deletion (Delete):&lt;/strong&gt; O(1)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Retrieval (Get):&lt;/strong&gt; O(1)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This means that on average, the time taken for these operations does not grow with the number of items stored in the hash table. Whether you have 10 items or 10 million, finding or adding an item takes roughly the same amount of time. This is a monumental achievement in data structure design.&lt;/p&gt;
&lt;h3 id="worst-case-performance"&gt;Worst Case Performance&lt;/h3&gt;
&lt;p&gt;The efficiency of a hash table can drastically degrade in the worst case, particularly when many collisions occur.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Worst Case for Chaining:&lt;/strong&gt; If all keys hash to the same bucket, the hash table effectively devolves into a single linked list. In this scenario, insertion, deletion, and retrieval all become O(N), where N is the number of elements in the table. This is as slow as a linear search in an unsorted list.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Worst Case for Open Addressing:&lt;/strong&gt; If the table becomes nearly full or if a malicious attacker intentionally creates keys that cause maximal collisions (a "hash collision attack"), performance can also degrade to O(N).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;While rare in practice with well-designed hash functions and dynamic resizing, it's vital to be aware of these worst-case scenarios, especially in security-sensitive applications or environments with non-uniform data distributions.&lt;/p&gt;
&lt;h3 id="load-factor-balancing-efficiency"&gt;Load Factor: Balancing Efficiency&lt;/h3&gt;
&lt;p&gt;The &lt;strong&gt;load factor (α)&lt;/strong&gt; of a hash table is a critical metric that influences its performance. It's defined as:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;α = (Number of entries) / (Number of buckets)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Impact of Load Factor:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Low Load Factor (α &amp;lt;&amp;lt; 1):&lt;/strong&gt; Indicates many empty buckets. This means fewer collisions and faster average-case performance, but it wastes memory.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;High Load Factor (α &amp;gt;= 1):&lt;/strong&gt; Indicates a crowded table. More keys are hashing to the same buckets, leading to increased collisions and longer average probe sequences (for open addressing) or longer linked lists (for chaining). This degrades performance towards O(N).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To maintain optimal performance, hash tables dynamically resize their underlying array when the load factor exceeds a certain threshold (typically 0.7 to 0.75 for open addressing, and potentially higher for chaining). Resizing involves:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Creating a new, larger array (e.g., double the current size).&lt;/li&gt;
&lt;li&gt;Rehashing all existing key-value pairs from the old array into the new one.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This rehashing operation can be expensive (O(N) for N elements), but it's amortized over many insertions, ensuring that the average cost of an insertion remains O(1).&lt;/p&gt;
&lt;h2 id="common-implementations-and-data-structures"&gt;Common Implementations and Data Structures&lt;/h2&gt;
&lt;p&gt;Hash tables are so fundamental that they are built into the core libraries of most modern programming languages. While the underlying principles remain consistent, their specific implementations might vary slightly in naming and nuances.&lt;/p&gt;
&lt;h3 id="pythons-dictionaries"&gt;Python's Dictionaries&lt;/h3&gt;
&lt;p&gt;Python's &lt;code&gt;dict&lt;/code&gt; type is one of the most widely used and efficient implementations of a hash table. They are highly optimized and power much of Python's internal workings.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Implementation:&lt;/strong&gt; Internally, Python dictionaries use open addressing with a sophisticated probing strategy (a variant of double hashing with randomized perturbation since Python 3.6).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Key Restrictions:&lt;/strong&gt; Keys must be hashable. Immutable types (numbers, strings, tuples) are hashable. Mutable types (lists, dictionaries, sets) are not, because their hash value could change, breaking the lookup mechanism.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Performance:&lt;/strong&gt; Offers average O(1) for &lt;code&gt;get&lt;/code&gt;, &lt;code&gt;set&lt;/code&gt;, and &lt;code&gt;delete&lt;/code&gt; operations. Resizing occurs when the load factor reaches a certain threshold.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Python dictionary example&lt;/span&gt;
&lt;span class="n"&gt;my_dict&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;&amp;quot;apple&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;&amp;quot;banana&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;&amp;quot;cherry&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;apple&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="c1"&gt;# Output: 1&lt;/span&gt;
&lt;span class="n"&gt;my_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;date&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;     &lt;span class="c1"&gt;# Insertion&lt;/span&gt;
&lt;span class="k"&gt;del&lt;/span&gt; &lt;span class="n"&gt;my_dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;banana&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;   &lt;span class="c1"&gt;# Deletion&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="javas-hashmap"&gt;Java's HashMap&lt;/h3&gt;
&lt;p&gt;Java provides the &lt;code&gt;HashMap&lt;/code&gt; class in its &lt;code&gt;java.util&lt;/code&gt; package, which is a classic implementation of a hash table.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Implementation:&lt;/strong&gt; Uses chaining (linked lists) to handle collisions. From Java 8 onwards, if a bucket's linked list becomes too long (typically 8 nodes), it converts that linked list into a balanced tree (specifically, a Red-Black tree) to improve worst-case performance from O(N) to O(log N) for that bucket. This is a significant optimization.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Key Restrictions:&lt;/strong&gt; Keys must override &lt;code&gt;hashCode()&lt;/code&gt; and &lt;code&gt;equals()&lt;/code&gt; methods correctly to ensure proper functionality.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Performance:&lt;/strong&gt; Average O(1) for &lt;code&gt;get&lt;/code&gt;, &lt;code&gt;put&lt;/code&gt;, and &lt;code&gt;remove&lt;/code&gt;. Resizes when the load factor (default 0.75) is exceeded.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.HashMap&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;HashMapExample&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;apple&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;banana&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;cherry&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;apple&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Output: 1&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;banana&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// Deletion&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="cs-stdunordered_map"&gt;C++'s &lt;code&gt;std::unordered_map&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;In C++, the Standard Library offers &lt;code&gt;std::unordered_map&lt;/code&gt; (and &lt;code&gt;std::unordered_set&lt;/code&gt; for keys only) since C++11, which provides hash table functionality.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Implementation:&lt;/strong&gt; Typically uses chaining (linked lists) for collision resolution, though the C++ standard allows implementers some flexibility.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Key Restrictions:&lt;/strong&gt; Keys require a hash function (either provided by &lt;code&gt;std::hash&lt;/code&gt; for built-in types or user-defined for custom types) and an equality comparison operator (&lt;code&gt;operator==&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Performance:&lt;/strong&gt; Average O(1) for &lt;code&gt;insert&lt;/code&gt;, &lt;code&gt;erase&lt;/code&gt;, and &lt;code&gt;find&lt;/code&gt;. The load factor management and resizing strategy are implementation-defined but follow similar principles to other languages.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;string&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;unordered_map&amp;gt;&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;unordered_map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;apple&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;banana&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;cherry&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;apple&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Output: 1&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;myMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;erase&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;banana&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;                   &lt;/span&gt;&lt;span class="c1"&gt;// Deletion&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&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;h2 id="real-world-uses-of-hash-tables-practical-applications"&gt;Real-World Uses of Hash Tables: Practical Applications&lt;/h2&gt;
&lt;p&gt;The ubiquitous nature of hash tables means they are embedded in countless systems and applications we interact with daily. Their speed and efficiency make them indispensable. Here are some of the most significant &lt;strong&gt;Real-World Uses of Hash Tables&lt;/strong&gt;:&lt;/p&gt;
&lt;h3 id="database-indexing"&gt;Database Indexing&lt;/h3&gt;
&lt;p&gt;Databases frequently use hash tables (or hash indexes) to speed up data retrieval. When you query a database for a specific record using a primary key, a hash index can quickly point to the physical location of that record on disk. Instead of scanning an entire table, the database applies a hash function to your key, instantly getting the location. This drastically reduces query times for exact-match lookups. For instance, finding a user record by &lt;code&gt;user_id&lt;/code&gt; in a massive table can leverage a hash index for O(1) average time access.&lt;/p&gt;
&lt;h3 id="caching-systems"&gt;Caching Systems&lt;/h3&gt;
&lt;p&gt;Caches are temporary storage areas that hold frequently accessed data to serve requests faster. Hash tables are perfect for this. When a web server or application needs to fetch data, it first checks a cache. The URL or data ID acts as the key, and the cached content is the value. If the key is found, the data is served from the cache (O(1) lookup); otherwise, it's fetched from the slower primary source and then added to the cache. Systems like Redis, Memcached, and even your browser's cache heavily rely on hash table principles.&lt;/p&gt;
&lt;h3 id="symbol-tables-in-compilers"&gt;Symbol Tables in Compilers&lt;/h3&gt;
&lt;p&gt;Compilers and interpreters use symbol tables to store information about identifiers (variables, function names, classes) used in a program. Each identifier is a key, and its associated information (data type, scope, memory address) is the value. When the compiler encounters an identifier, it performs a quick hash table lookup to retrieve its properties, enabling efficient semantic analysis and code generation.&lt;/p&gt;
&lt;h3 id="unique-data-identification"&gt;Unique Data Identification&lt;/h3&gt;
&lt;p&gt;Hash tables are excellent for quickly checking if an item has been seen before or for identifying unique elements in a collection. For example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Deduplication:&lt;/strong&gt; When importing a large dataset, a hash set (a hash table storing only keys) can efficiently track seen items to prevent duplicates.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Spell Checkers:&lt;/strong&gt; A dictionary of correctly spelled words can be loaded into a hash set. When checking a word, a quick O(1) lookup determines if it's valid.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Password Hashing:&lt;/strong&gt; While not storing passwords directly in a hash table, the concept of hashing is fundamental to securing passwords. User passwords are fed into a cryptographic hash function (a specific type of hash function designed for security) to produce a fixed-size hash. This hash is stored, not the password itself, protecting against data breaches.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="network-routers-and-firewalls"&gt;Network Routers and Firewalls&lt;/h3&gt;
&lt;p&gt;Network devices like routers and firewalls use hash tables for fast lookup of routing tables or firewall rules.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Routing Tables:&lt;/strong&gt; Routers maintain tables that map destination IP addresses to the next hop. A hash table can quickly find the appropriate outgoing interface for a given IP packet.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Firewall Rules:&lt;/strong&gt; Firewalls use hash tables to store and quickly check security rules based on source/destination IP, port, and protocol. This enables high-speed packet filtering, which is critical for network performance and security.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="cryptography-and-data-integrity"&gt;Cryptography and Data Integrity&lt;/h3&gt;
&lt;p&gt;While cryptographic hash functions (like SHA-256 or MD5) are distinct from the simple hash functions used in data structures, they share the underlying principle of mapping arbitrary-sized data to a fixed-size output. These functions are critical for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Digital Signatures:&lt;/strong&gt; Verifying the authenticity and integrity of digital documents.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Blockchain Technology:&lt;/strong&gt; Each block in a blockchain contains a hash of the previous block, creating an immutable chain of records.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Integrity Checks:&lt;/strong&gt; Ensuring that a file has not been tampered with by comparing its current hash with a known good hash.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="advantages-and-disadvantages-of-hash-tables"&gt;Advantages and Disadvantages of Hash Tables&lt;/h2&gt;
&lt;p&gt;Like any data structure, hash tables come with a set of benefits and trade-offs that developers must consider.&lt;/p&gt;
&lt;h3 id="key-advantages"&gt;Key Advantages&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Exceptional Average-Case Performance:&lt;/strong&gt; As discussed, hash tables provide O(1) average time complexity for insertions, deletions, and lookups, making them incredibly fast for many common operations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficient Data Retrieval:&lt;/strong&gt; When you need to quickly retrieve a value associated with a unique key, hash tables are often the best choice.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Versatility:&lt;/strong&gt; They can store a wide variety of key-value pairs, from simple primitive types to complex objects.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Foundation for Other Structures:&lt;/strong&gt; Hash tables are often used internally to implement other data structures, such as hash sets or memoization tables for dynamic programming.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Simplicity of API:&lt;/strong&gt; The interface for interacting with hash tables (e.g., &lt;code&gt;put(key, value)&lt;/code&gt;, &lt;code&gt;get(key)&lt;/code&gt;, &lt;code&gt;remove(key)&lt;/code&gt;) is generally straightforward and intuitive.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="potential-disadvantages"&gt;Potential Disadvantages&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Worst-Case Performance:&lt;/strong&gt; Despite excellent average-case performance, malicious inputs or poorly designed hash functions can lead to O(N) worst-case performance, especially if collision resolution is inefficient.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory Overhead:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Chaining:&lt;/strong&gt; Requires extra memory for pointers in linked lists.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Open Addressing:&lt;/strong&gt; Can require the table to be significantly larger than the number of stored elements to maintain a low load factor, leading to unused space.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No Ordered Data:&lt;/strong&gt; Hash tables do not maintain any inherent order of keys. If you need to retrieve elements in sorted order, you would need to sort the keys separately, which incurs additional cost. For ordered key-value storage, &lt;a href="/binary-search-tree-step-by-step-implementation-guide/"&gt;balanced binary search trees&lt;/a&gt; (like Red-Black Trees) are more appropriate.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Complexity of Collision Resolution:&lt;/strong&gt; Designing a good hash function and an efficient collision resolution strategy is crucial and can be complex. Improper implementation can significantly degrade performance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Rehashing Cost:&lt;/strong&gt; When a hash table needs to resize (rehash), the entire process of inserting all existing elements into a new, larger table can be computationally expensive. While amortized to O(1) over many operations, a single rehashing event can cause a temporary performance spike.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hash Function Security:&lt;/strong&gt; Poorly chosen or predictable hash functions can be vulnerable to hash collision attacks, where an attacker crafts inputs that intentionally cause many collisions, slowing down the system.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="advanced-concepts-and-future-outlook"&gt;Advanced Concepts and Future Outlook&lt;/h2&gt;
&lt;p&gt;The core principles of hash tables are well-established, but research and development continue to push their boundaries, particularly in specialized contexts.&lt;/p&gt;
&lt;h3 id="perfect-hashing"&gt;Perfect Hashing&lt;/h3&gt;
&lt;p&gt;Perfect hashing is a technique where a hash function is found such that there are &lt;em&gt;no collisions&lt;/em&gt; for a given static set of keys. This guarantees O(1) worst-case lookup time. While highly desirable, finding a perfect hash function is computationally intensive and usually only feasible for static, unchanging sets of keys. It's often achieved using a two-level hashing scheme.&lt;/p&gt;
&lt;h3 id="cuckoo-hashing"&gt;Cuckoo Hashing&lt;/h3&gt;
&lt;p&gt;Cuckoo hashing is an open addressing scheme that uses two (or more) hash functions. Each key has two possible locations. When a key needs to be inserted, it tries to occupy its primary location. If that location is occupied, it "kicks out" the existing key, which then tries to move to its alternate location using the second hash function. This process continues like a cuckoo bird pushing eggs out of a nest.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Guarantees O(1) worst-case lookup time (unlike standard open addressing or chaining).&lt;/li&gt;
&lt;li&gt;High space utilization.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;More complex to implement.&lt;/li&gt;
&lt;li&gt;Insertions can sometimes involve long "cuckoo cycles" leading to rehashes, though this is rare.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="distributed-hash-tables-dhts"&gt;Distributed Hash Tables (DHTs)&lt;/h3&gt;
&lt;p&gt;DHTs are a class of decentralized distributed systems that provide a lookup service similar to a hash table. They are designed to scale to extremely large numbers of nodes and store vast amounts of data. In a DHT, key-value pairs are distributed across many nodes in a network. Any node can retrieve the value associated with a given key.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Applications:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Peer-to-peer file sharing:&lt;/strong&gt; BitTorrent uses DHTs to locate content.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Distributed storage:&lt;/strong&gt; Used in systems like Apache Cassandra and DynamoDB for data distribution and fault tolerance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Naming services:&lt;/strong&gt; Systems like IPFS use DHTs for content addressing.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="quantum-computing-and-hashing"&gt;Quantum Computing and Hashing&lt;/h3&gt;
&lt;p&gt;The advent of quantum computing raises interesting questions for cryptographic hashing. Shor's algorithm can break asymmetric encryption, but Grover's algorithm could potentially speed up pre-image attacks on cryptographic hash functions. This means quantum computers might, in the future, challenge the security assumptions underlying current hashing algorithms, requiring the development of "quantum-resistant" hash functions. For data structure hash tables, the impact is less direct, as they primarily rely on speed and collision avoidance, not cryptographic security.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What are hash tables used for?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Hash tables are fundamental for fast data storage and retrieval in a wide array of applications. This includes database indexing, caching systems, symbol tables in compilers, unique data identification, and network routing in firewalls and routers, among others. They excel at providing near-instantaneous access to data based on a given key.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What are the main collision resolution strategies?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The two primary strategies for resolving hash collisions are chaining and open addressing. Chaining involves storing multiple key-value pairs that hash to the same index in a linked list within that array slot. Open addressing, on the other hand, finds an alternative empty slot directly within the hash table's array using probing techniques like linear, quadratic, or double hashing.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the average time complexity of hash table operations?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Under ideal conditions, which involve a well-designed hash function and proper load factor management, hash tables offer an average O(1) (constant time) complexity for fundamental operations like insertion, deletion, and retrieval. This means the time taken for these operations generally does not increase with the size of the dataset.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Hash_table"&gt;Hash table - Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/hashing-data-structure/"&gt;Hashing in Data Structure - GeeksForGeeks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.freecodecamp.org/news/what-is-a-hash-table-a-detailed-explanation/"&gt;What Is a Hash Table? A Detailed Explanation - freeCodeCamp&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries"&gt;Python Dictionaries - Official Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html"&gt;Java HashMap Class - Oracle Documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Technology"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/hash-tables-comprehensive-guide-real-world-uses.webp" width="1200"/><media:title type="plain">Hash Tables: Comprehensive Guide &amp; Real-World Uses</media:title><media:description type="plain">Dive deep into Hash Tables: Comprehensive Guide &amp; Real-World Uses. Explore their mechanics, collision resolution, performance, and essential applications in ...</media:description></entry><entry><title>Binary Search Tree: A Step-by-Step Implementation Guide for Developers</title><link href="https://analyticsdrive.tech/binary-search-tree-step-by-step-implementation-guide/" rel="alternate"/><published>2026-03-21T22:06:00+05:30</published><updated>2026-03-21T22:06:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-21:/binary-search-tree-step-by-step-implementation-guide/</id><summary type="html">&lt;p&gt;Dive deep into the Binary Search Tree: A Step-by-Step Implementation Guide. Learn its core concepts, operations, and practical applications for efficient dat...&lt;/p&gt;</summary><content type="html">&lt;p&gt;For developers aiming to master efficient data structures, this &lt;strong&gt;Binary Search Tree: A Step-by-Step Implementation Guide&lt;/strong&gt; serves as a cornerstone for robust software engineering. Among these, the Binary Search Tree (BST) stands out as a fundamental yet powerful structure for organizing and retrieving data quickly. Its ability to maintain sorted data while allowing for dynamic insertions and deletions makes it invaluable in various computing scenarios. This article is designed to equip developers with a deep understanding and practical skills for its real-world application.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-foundational-concept-what-is-a-binary-search-tree"&gt;The Foundational Concept: What is a Binary Search Tree?&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#core-properties-of-a-binary-search-tree"&gt;Core Properties of a Binary Search Tree&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#anatomy-of-a-node-building-blocks-of-a-bst"&gt;Anatomy of a Node: Building Blocks of a BST&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#deep-dive-into-binary-search-tree-a-step-by-step-implementation-guide"&gt;Deep Dive into Binary Search Tree: A Step-by-Step Implementation Guide&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-initializing-the-bst"&gt;1. Initializing the BST&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-inserting-a-node-the-insert-operation"&gt;2. Inserting a Node: The insert Operation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-searching-for-a-node-the-search-operation"&gt;3. Searching for a Node: The search Operation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-deleting-a-node-the-delete-operation"&gt;4. Deleting a Node: The delete Operation&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#case-1-node-to-be-deleted-is-a-leaf-node-0-children"&gt;Case 1: Node to be Deleted is a Leaf Node (0 Children)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#case-2-node-to-be-deleted-has-one-child"&gt;Case 2: Node to be Deleted Has One Child&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#case-3-node-to-be-deleted-has-two-children"&gt;Case 3: Node to be Deleted Has Two Children&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#traversing-the-binary-search-tree-in-order-pre-order-post-order"&gt;Traversing the Binary Search Tree: In-order, Pre-order, Post-order&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-in-order-traversal"&gt;1. In-order Traversal&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-pre-order-traversal"&gt;2. Pre-order Traversal&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-post-order-traversal"&gt;3. Post-order Traversal&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-problem-of-skewed-trees-and-balancing"&gt;The Problem of Skewed Trees and Balancing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-binary-search-trees"&gt;Real-World Applications of Binary Search Trees&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#advantages-and-disadvantages-of-binary-search-trees"&gt;Advantages and Disadvantages of Binary Search Trees&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#advantages"&gt;Advantages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#disadvantages"&gt;Disadvantages&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#beyond-the-basics-further-exploration-and-next-steps"&gt;Beyond the Basics: Further Exploration and Next Steps&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id="the-foundational-concept-what-is-a-binary-search-tree"&gt;The Foundational Concept: What is a Binary Search Tree?&lt;/h2&gt;
&lt;p&gt;At its heart, a Binary Search Tree (BST) is a hierarchical data structure that organizes data in a way that facilitates efficient searching, insertion, and deletion operations. Imagine a meticulously organized library where every book is placed according to specific rules, ensuring you can always find what you're looking for without sifting through every single shelf. That's essentially what a BST does for your data.&lt;/p&gt;
&lt;p&gt;Unlike linear data structures like arrays or linked lists, which might require scanning through elements sequentially in the worst case (O(n)), a BST leverages a sorted arrangement to achieve logarithmic time complexity (O(log n)) for most operations in its average case. This significant performance boost makes BSTs a go-to choice for managing dynamic datasets where speed is paramount.&lt;/p&gt;
&lt;h3 id="core-properties-of-a-binary-search-tree"&gt;Core Properties of a Binary Search Tree&lt;/h3&gt;
&lt;p&gt;To qualify as a Binary Search Tree, a tree must adhere to two fundamental properties that govern the placement of every node:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Left Child Property:&lt;/strong&gt;
    For any given node, all values in its left subtree must be strictly less than the node's own value.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Right Child Property:&lt;/strong&gt;
    For any given node, all values in its right subtree must be strictly greater than the node's own value.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;No Duplicates (Common Convention):&lt;/strong&gt;
    While some implementations allow duplicates (usually by placing them in the right subtree), the most common and textbook definition of a BST assumes all node values are unique. For simplicity and clarity in this guide, we will adhere to the "no duplicates" convention.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These properties are recursively applied to every node in the tree, meaning that every subtree within a BST is itself a Binary Search Tree. This recursive nature is crucial for understanding and implementing its operations efficiently.&lt;/p&gt;
&lt;h2 id="anatomy-of-a-node-building-blocks-of-a-bst"&gt;Anatomy of a Node: Building Blocks of a BST&lt;/h2&gt;
&lt;p&gt;Before diving into operations, let's understand the basic unit of a Binary Search Tree: the node. Each node typically encapsulates three pieces of information:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;data&lt;/code&gt; (or &lt;code&gt;key&lt;/code&gt;, &lt;code&gt;value&lt;/code&gt;):&lt;/strong&gt;
    The actual data element stored in the node. This is the value that determines the node's position within the tree according to the BST properties.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;left&lt;/code&gt;:&lt;/strong&gt;
    A pointer or reference to the left child node. If there is no left child, this pointer will typically be &lt;code&gt;None&lt;/code&gt; (or &lt;code&gt;null&lt;/code&gt; in other languages).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;right&lt;/code&gt;:&lt;/strong&gt;
    A pointer or reference to the right child node. Similarly, if there is no right child, this pointer will be &lt;code&gt;None&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In Python, we can define a simple &lt;code&gt;Node&lt;/code&gt; class like this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This &lt;code&gt;Node&lt;/code&gt; class serves as the fundamental building block. Next, we'll create a &lt;code&gt;BinarySearchTree&lt;/code&gt; class to manage these nodes and implement the various operations.&lt;/p&gt;
&lt;h2 id="deep-dive-into-binary-search-tree-a-step-by-step-implementation-guide"&gt;Deep Dive into Binary Search Tree: A Step-by-Step Implementation Guide&lt;/h2&gt;
&lt;p&gt;Now, let's get into the practical implementation of the core operations for a Binary Search Tree. We'll implement insertion, search, and deletion, which are the most critical functions for managing data in a BST. For clarity, we will use Python.&lt;/p&gt;
&lt;h3 id="1-initializing-the-bst"&gt;1. Initializing the BST&lt;/h3&gt;
&lt;p&gt;Our &lt;code&gt;BinarySearchTree&lt;/code&gt; class will primarily hold a reference to the &lt;code&gt;root&lt;/code&gt; node. When the tree is empty, the &lt;code&gt;root&lt;/code&gt; will be &lt;code&gt;None&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BinarySearchTree&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="2-inserting-a-node-the-insert-operation"&gt;2. Inserting a Node: The &lt;code&gt;insert&lt;/code&gt; Operation&lt;/h3&gt;
&lt;p&gt;Inserting a new node into a BST follows a very specific path to maintain the tree's ordered properties. The process involves traversing the tree from the root, comparing the new key with the current node's key, and deciding whether to go left or right.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step-by-Step Insertion Logic:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Start at the Root:&lt;/strong&gt;
    Begin the search for the insertion point at the &lt;code&gt;root&lt;/code&gt; of the tree.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Empty Tree Check:&lt;/strong&gt;
    If the tree is empty (i.e., &lt;code&gt;root&lt;/code&gt; is &lt;code&gt;None&lt;/code&gt;), the new node becomes the &lt;code&gt;root&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Compare and Traverse:&lt;/strong&gt;
    If the tree is not empty, compare the new key (&lt;code&gt;new_key&lt;/code&gt;) with the current node's key (&lt;code&gt;current_node.key&lt;/code&gt;).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;new_key &amp;lt; current_node.key&lt;/code&gt;: The new key belongs in the left subtree.&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;current_node.left&lt;/code&gt; is &lt;code&gt;None&lt;/code&gt;, insert the &lt;code&gt;new_key&lt;/code&gt; as the left child.&lt;/li&gt;
&lt;li&gt;Otherwise, move to &lt;code&gt;current_node.left&lt;/code&gt; and repeat the comparison.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;new_key &amp;gt; current_node.key&lt;/code&gt;: The new key belongs in the right subtree.&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;current_node.right&lt;/code&gt; is &lt;code&gt;None&lt;/code&gt;, insert the &lt;code&gt;new_key&lt;/code&gt; as the right child.&lt;/li&gt;
&lt;li&gt;Otherwise, move to &lt;code&gt;current_node.right&lt;/code&gt; and repeat the comparison.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;new_key == current_node.key&lt;/code&gt;: (Assuming no duplicates) The key already exists. You can choose to ignore, raise an error, or update the node. For this guide, we'll simply ignore duplicate insertions.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Python Implementation of &lt;code&gt;insert&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We can implement &lt;code&gt;insert&lt;/code&gt; recursively or iteratively. The recursive approach is often more elegant and easier to understand for tree operations.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BinarySearchTree&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Public method to insert a key.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Helper method for recursive insertion.&lt;/span&gt;
&lt;span class="sd"&gt;        Returns the (potentially new) root of the subtree.&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="c1"&gt;# Base case: If the current node is None, we&amp;#39;ve found the insertion point.&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Recursive step: Traverse left or right based on key comparison.&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_insert_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="c1"&gt;# Else: key is equal to node.key, duplicate ignored as per our convention&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="3-searching-for-a-node-the-search-operation"&gt;3. Searching for a Node: The &lt;code&gt;search&lt;/code&gt; Operation&lt;/h3&gt;
&lt;p&gt;Searching for a specific key in a BST mirrors the insertion process, leveraging the tree's sorted structure to quickly narrow down the search space.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step-by-Step Search Logic:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Start at the Root:&lt;/strong&gt;
    Begin the search at the &lt;code&gt;root&lt;/code&gt; of the tree.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Compare Current Node:&lt;/strong&gt;
    Compare the target key (&lt;code&gt;target_key&lt;/code&gt;) with the current node's key (&lt;code&gt;current_node.key&lt;/code&gt;).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Found:&lt;/strong&gt;
    If &lt;code&gt;target_key == current_node.key&lt;/code&gt;, the key is found. Return &lt;code&gt;True&lt;/code&gt; (or the node itself).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Traverse Left:&lt;/strong&gt;
    If &lt;code&gt;target_key &amp;lt; current_node.key&lt;/code&gt;, the target key, if it exists, must be in the left subtree. Move to &lt;code&gt;current_node.left&lt;/code&gt; and repeat.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Traverse Right:&lt;/strong&gt;
    If &lt;code&gt;target_key &amp;gt; current_node.key&lt;/code&gt;, the target key, if it exists, must be in the right subtree. Move to &lt;code&gt;current_node.right&lt;/code&gt; and repeat.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Not Found:&lt;/strong&gt;
    If you reach a &lt;code&gt;None&lt;/code&gt; node (i.e., &lt;code&gt;current_node&lt;/code&gt; becomes &lt;code&gt;None&lt;/code&gt;) and haven't found the key, it means the key does not exist in the tree. Return &lt;code&gt;False&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Python Implementation of &lt;code&gt;search&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Public method to search for a key.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Helper method for recursive search.&lt;/span&gt;
&lt;span class="sd"&gt;        Returns True if key is found, False otherwise.&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="c1"&gt;# Base case 1: Key not found, reached a None node.&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;

        &lt;span class="c1"&gt;# Base case 2: Key found.&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;

        &lt;span class="c1"&gt;# Recursive step: Traverse left or right.&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# key &amp;gt; node.key&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_search_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="4-deleting-a-node-the-delete-operation"&gt;4. Deleting a Node: The &lt;code&gt;delete&lt;/code&gt; Operation&lt;/h3&gt;
&lt;p&gt;Deleting a node from a BST is the most complex operation because it must maintain the BST properties while removing an element. There are three main scenarios to consider based on the number of children the node to be deleted has:&lt;/p&gt;
&lt;h4 id="case-1-node-to-be-deleted-is-a-leaf-node-0-children"&gt;Case 1: Node to be Deleted is a Leaf Node (0 Children)&lt;/h4&gt;
&lt;p&gt;If the node to be deleted has no children, simply remove it by setting its parent's pointer (either &lt;code&gt;left&lt;/code&gt; or &lt;code&gt;right&lt;/code&gt;) to &lt;code&gt;None&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id="case-2-node-to-be-deleted-has-one-child"&gt;Case 2: Node to be Deleted Has One Child&lt;/h4&gt;
&lt;p&gt;If the node to be deleted has only one child, replace the node with its child. The parent of the deleted node will now point to the deleted node's child.&lt;/p&gt;
&lt;h4 id="case-3-node-to-be-deleted-has-two-children"&gt;Case 3: Node to be Deleted Has Two Children&lt;/h4&gt;
&lt;p&gt;This is the trickiest case. When a node with two children is deleted, we need to find a replacement node that can take its place without violating the BST properties. The standard approach is to find the &lt;strong&gt;in-order successor&lt;/strong&gt; (the smallest node in the right subtree) or the &lt;strong&gt;in-order predecessor&lt;/strong&gt; (the largest node in the left subtree).&lt;/p&gt;
&lt;p&gt;Let's choose the &lt;strong&gt;in-order successor&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Find the minimum node in the right subtree of the node to be deleted. This successor node will always have at most one right child (it cannot have a left child, otherwise it wouldn't be the minimum).&lt;/li&gt;
&lt;li&gt;Copy the &lt;code&gt;key&lt;/code&gt; of the in-order successor to the node that is being logically "deleted".&lt;/li&gt;
&lt;li&gt;Recursively delete the in-order successor from the right subtree. This deletion will fall into Case 1 or Case 2.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Helper Function for &lt;code&gt;minValueNode&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We'll need a helper function to find the node with the minimum value in a given subtree. This will be used in Case 3.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_min_value_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Helper method to find the node with the minimum key in a subtree.&lt;/span&gt;
&lt;span class="sd"&gt;        The minimum node is always the leftmost node in a BST.&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Python Implementation of &lt;code&gt;delete&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;delete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Public method to delete a key.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Helper method for recursive deletion.&lt;/span&gt;
&lt;span class="sd"&gt;        Returns the (potentially new) root of the subtree after deletion.&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="c1"&gt;# Base case 1: If the node is None, key not found.&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;

        &lt;span class="c1"&gt;# Recursive step: Traverse left or right to find the node to delete.&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# key == node.key, this is the node to be deleted&lt;/span&gt;

            &lt;span class="c1"&gt;# Case 1: Node with only one child or no child&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;temp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;
                &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt; &lt;span class="c1"&gt;# For garbage collection, though Python handles it.&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;temp&lt;/span&gt;
            &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;temp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;
                &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;temp&lt;/span&gt;

            &lt;span class="c1"&gt;# Case 3: Node with two children&lt;/span&gt;
            &lt;span class="c1"&gt;# Find the in-order successor (smallest in the right subtree)&lt;/span&gt;
            &lt;span class="n"&gt;temp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_min_value_node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

            &lt;span class="c1"&gt;# Copy the in-order successor&amp;#39;s key to this node&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;

            &lt;span class="c1"&gt;# Delete the in-order successor from the right subtree&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_delete_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h2 id="traversing-the-binary-search-tree-in-order-pre-order-post-order"&gt;Traversing the Binary Search Tree: In-order, Pre-order, Post-order&lt;/h2&gt;
&lt;p&gt;Traversal refers to the process of visiting each node in the tree exactly once. There are three common ways to traverse a BST, each yielding a different order of nodes, useful for different purposes. These are typically implemented recursively.&lt;/p&gt;
&lt;h3 id="1-in-order-traversal"&gt;1. In-order Traversal&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Visits the left subtree, then the root, then the right subtree. This traversal always yields the nodes in &lt;strong&gt;sorted order&lt;/strong&gt; for a BST. It's like reading a dictionary from A to Z.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Order:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Left -&amp;gt; Root -&amp;gt; Right&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use Cases:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Retrieving sorted data, converting BST to a sorted list.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Python Implementation:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;inorder_traversal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Public method for in-order traversal.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_inorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_inorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="2-pre-order-traversal"&gt;2. Pre-order Traversal&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Visits the root first, then the left subtree, then the right subtree.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Order:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Root -&amp;gt; Left -&amp;gt; Right&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use Cases:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Creating a copy of the tree, expressing tree structure (useful for prefix expressions).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Python Implementation:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;preorder_traversal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Public method for pre-order traversal.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_preorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_preorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_preorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_preorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="3-post-order-traversal"&gt;3. Post-order Traversal&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Visits the left subtree, then the right subtree, then the root.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Order:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Left -&amp;gt; Right -&amp;gt; Root&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use Cases:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Deleting the tree (delete children before the parent), evaluating postfix expressions.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Python Implementation:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;postorder_traversal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Public method for post-order traversal.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_postorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_postorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_postorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_postorder_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h2 id="time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the efficiency of BST operations is crucial for deciding when to use them. For a deeper dive into measuring algorithm efficiency, consider our guide on &lt;a href="/big-o-notation-explained-beginner-guide-complexity/"&gt;Big O Notation Explained: A Beginner's Guide to Complexity&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;The time complexity of BST operations (search, insert, delete) largely depends on the height of the tree.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Best Case (Balanced Tree):&lt;/strong&gt; When the tree is perfectly balanced (like a complete binary tree), its height is approximately log₂N, where N is the number of nodes. In this ideal scenario, operations take &lt;strong&gt;O(log N)&lt;/strong&gt; time because at each step, we eliminate half of the remaining nodes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Worst Case (Skewed Tree):&lt;/strong&gt; If the elements are inserted in strictly ascending or descending order, the BST degenerates into a linked list. In this case, the height of the tree becomes N, and operations can take &lt;strong&gt;O(N)&lt;/strong&gt; time, similar to a linear search.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Average Case:&lt;/strong&gt; On average, assuming random insertions, a BST's height tends to be logarithmic, leading to an average time complexity of &lt;strong&gt;O(log N)&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Traversal (In-order, Pre-order, Post-order):&lt;/strong&gt; All traversals visit each node exactly once. Thus, their time complexity is always &lt;strong&gt;O(N)&lt;/strong&gt;, regardless of the tree's balance.&lt;/p&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Nodes:&lt;/strong&gt; The space required to store the nodes themselves is directly proportional to the number of nodes in the tree, so it's &lt;strong&gt;O(N)&lt;/strong&gt;. Each node stores its key and two pointers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursion Stack:&lt;/strong&gt; For recursive implementations (like the ones shown above), the space complexity for the recursion stack depends on the height of the tree.&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Best Case (Balanced Tree):&lt;/strong&gt; O(log N)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Worst Case (Skewed Tree):&lt;/strong&gt; O(N)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;strong&gt;O(N)&lt;/strong&gt; space complexity for storing the nodes is generally dominant, but the recursive stack space is a consideration, especially for very deep, skewed trees.&lt;/p&gt;
&lt;h2 id="the-problem-of-skewed-trees-and-balancing"&gt;The Problem of Skewed Trees and Balancing&lt;/h2&gt;
&lt;p&gt;As highlighted in the complexity analysis, the performance of a BST can degrade significantly to O(N) in the worst-case scenario where the tree becomes skewed. A skewed tree essentially acts like a linked list, losing all the benefits of its tree structure. This often occurs when data is inserted in an already sorted (or reverse-sorted) order. For more foundational information on binary structures, you can read our article on &lt;a href="/demystifying-binary-trees-structure-traversal-use/"&gt;Demystifying Binary Trees: Structure, Traversal, &amp;amp; Use Explained&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;To mitigate this problem, advanced versions of BSTs, known as &lt;strong&gt;self-balancing BSTs&lt;/strong&gt;, were developed. These trees automatically perform rotations and other operations to maintain a relatively balanced structure after insertions and deletions, guaranteeing O(log N) time complexity for operations in all cases (worst, average, and best).&lt;/p&gt;
&lt;p&gt;Prominent examples of self-balancing BSTs include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;AVL Trees:&lt;/strong&gt;
    These trees maintain a "height balance factor" for each node, ensuring that the height difference between the left and right subtrees never exceeds one.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Red-Black Trees:&lt;/strong&gt;
    These are more complex but widely used, particularly in standard library implementations (e.g., C++ &lt;code&gt;std::map&lt;/code&gt;, Java &lt;code&gt;TreeMap&lt;/code&gt;). They use a coloring scheme (red or black nodes) and specific rules to ensure balance.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;While this guide focuses on the fundamental, unbalanced Binary Search Tree: A Step-by-Step Implementation Guide, it's essential for any serious developer to be aware of self-balancing trees as the practical solution for real-world scenarios requiring guaranteed logarithmic performance.&lt;/p&gt;
&lt;h2 id="real-world-applications-of-binary-search-trees"&gt;Real-World Applications of Binary Search Trees&lt;/h2&gt;
&lt;p&gt;Despite the potential for skewing, the fundamental BST concept and its self-balancing derivatives are foundational to many computing applications. Here are a few prominent examples:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Database Indexing:&lt;/strong&gt;
    Databases often use tree-like structures (specifically B-trees or B+ trees, which are generalized BSTs) to index records. This allows for extremely fast retrieval of data based on a key, without scanning entire tables.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;File Systems:&lt;/strong&gt;
    Directories and files in a file system can be organized using tree structures, making it efficient to locate files and folders by name.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Symbol Tables:&lt;/strong&gt;
    Compilers and interpreters use symbol tables to store information about variables, functions, and classes. BSTs or other efficient structures like &lt;a href="/hash-tables-deep-dive-how-they-work-use-cases/"&gt;Hash Tables: Deep Dive into Their Inner Workings &amp;amp; Use Cases&lt;/a&gt; are commonly employed for quick lookup of these symbols.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Routing Tables:&lt;/strong&gt;
    Network routers use data structures similar to BSTs to store and quickly search for the optimal path to forward data packets.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Set and Map Implementations:&lt;/strong&gt;
    Many programming languages' standard libraries provide &lt;code&gt;Set&lt;/code&gt; and &lt;code&gt;Map&lt;/code&gt; (or &lt;code&gt;Dictionary&lt;/code&gt;) data structures that are implemented using self-balancing BSTs (like Red-Black trees) to offer ordered storage and efficient key-value lookups.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Graphical User Interfaces:&lt;/strong&gt;
    Components in GUI toolkits sometimes use tree structures to manage the hierarchy of widgets on a screen, allowing for efficient rendering and event handling.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The efficiency of BST operations, particularly for ordered data, makes them a cornerstone in various algorithms and system designs.&lt;/p&gt;
&lt;h2 id="advantages-and-disadvantages-of-binary-search-trees"&gt;Advantages and Disadvantages of Binary Search Trees&lt;/h2&gt;
&lt;p&gt;Like any data structure, BSTs come with their own set of strengths and weaknesses.&lt;/p&gt;
&lt;h3 id="advantages"&gt;Advantages&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Efficient Searching:&lt;/strong&gt;
    For balanced trees, search, insertion, and deletion operations have an average time complexity of O(log N), which is highly efficient for large datasets.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Ordered Data Retrieval:&lt;/strong&gt;
    In-order traversal naturally retrieves data in sorted order, making BSTs ideal for applications requiring sorted lists.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Dynamic Data Management:&lt;/strong&gt;
    Unlike arrays, BSTs are dynamic. They can grow or shrink as needed, efficiently accommodating insertions and deletions without requiring resizing or extensive re-arrangement of elements.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Foundation for More Complex Structures:&lt;/strong&gt;
    BSTs form the basis for many more advanced data structures, including self-balancing trees (AVL, Red-Black), B-trees, and treaps.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="disadvantages"&gt;Disadvantages&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Worst-Case Performance:&lt;/strong&gt;
    The primary drawback is its worst-case time complexity of O(N) when the tree becomes highly skewed. This can happen if elements are inserted in an already sorted order, degrading performance to that of a linked list.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Balancing Overhead:&lt;/strong&gt;
    To guarantee O(log N) performance, self-balancing mechanisms must be implemented, which adds complexity and some computational overhead to insertion and deletion operations.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Memory Overhead:&lt;/strong&gt;
    Each node requires additional memory for its pointers (left and right children) beyond just the data itself. For very small data items, this overhead can be relatively significant.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Not Cache Friendly:&lt;/strong&gt;
    Due to their scattered memory allocation, BSTs can exhibit poor cache performance compared to array-based structures, which store elements contiguously.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Understanding these trade-offs is crucial for making informed decisions about data structure selection in software development.&lt;/p&gt;
&lt;h2 id="beyond-the-basics-further-exploration-and-next-steps"&gt;Beyond the Basics: Further Exploration and Next Steps&lt;/h2&gt;
&lt;p&gt;Having understood the core concepts and implementation of a basic Binary Search Tree, your journey into efficient data structures is just beginning. To truly master tree-based structures and unlock their full potential, consider exploring these advanced topics:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Self-Balancing Binary Search Trees:&lt;/strong&gt;
    Dive into the intricacies of AVL Trees and Red-Black Trees. Implementing these from scratch is a significant challenge but provides invaluable insights into advanced tree manipulation and balancing algorithms.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;B-Trees and B+ Trees:&lt;/strong&gt;
    These are generalizations of BSTs designed specifically for disk-based storage systems like databases, where minimizing disk I/O operations is critical. They are not binary (can have more than two children per node) and are optimized for block-based storage.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Heaps:&lt;/strong&gt;
    A special type of binary tree that satisfies the heap property (parent is always greater/smaller than its children). Heaps are crucial for implementing priority queues and efficient sorting algorithms like Heapsort.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Tries (Prefix Trees):&lt;/strong&gt;
    Specialized tree structures used for efficient retrieval of keys in a dataset of strings. They are particularly useful for tasks like autocomplete and spell checkers.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Segment Trees and Fenwick Trees (BITs):&lt;/strong&gt;
    Advanced tree structures used in competitive programming for efficiently querying and updating ranges on an array.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The principles you've learned here, especially recursion and careful pointer manipulation, will be fundamental as you explore these more sophisticated data structures. They represent the continuous evolution of computer science in the quest for ever more efficient data management.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The Binary Search Tree is a cornerstone data structure in computer science, offering a powerful paradigm for organizing and managing dynamic datasets. Through this &lt;strong&gt;Binary Search Tree: A Step-by-Step Implementation Guide&lt;/strong&gt;, we've explored its fundamental properties, delved into the creation of its core building blocks (nodes), and walked through the practical Python implementation of its essential operations: insertion, search, and the more complex deletion. We also covered various traversal methods and analyzed the crucial time and space complexities that dictate its performance.&lt;/p&gt;
&lt;p&gt;While basic BSTs offer excellent average-case performance, it's vital to recognize the potential for performance degradation in skewed scenarios and to consider self-balancing trees for robust, guaranteed logarithmic efficiency in production environments. By mastering the concepts presented here, developers gain an indispensable tool for designing efficient algorithms and building high-performance applications, setting a strong foundation for further exploration into the vast and fascinating world of advanced data structures.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the main advantage of a Binary Search Tree?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A BST allows for efficient searching, insertion, and deletion operations, typically achieving O(log N) time complexity in the average case due to its sorted, hierarchical structure. This makes it ideal for managing dynamic datasets where quick access and modification are necessary.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the worst-case performance of a BST, and why?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: In the worst case, a BST can degenerate into a linked list if elements are inserted in a strictly sorted (ascending or descending) order. This scenario leads to O(N) time complexity for operations, as the tree loses its balanced, hierarchical advantage.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: How do self-balancing BSTs improve performance?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Self-balancing BSTs, such as AVL trees and Red-Black trees, automatically perform rotations and other structural adjustments after insertions and deletions. This ensures that the tree remains relatively balanced, guaranteeing O(log N) performance for operations in all cases, including worst-case data input.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/binary-search-tree-data-structure/"&gt;GeeksforGeeks: Binary Search Tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.programiz.com/dsa/binary-search-tree"&gt;Programiz: Binary Search Tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Binary_search_tree"&gt;Wikipedia: Binary Search Tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=f-V3fD8B05Q"&gt;Stanford University CS106B Lecture: Binary Search Trees&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Competitive Programming"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/binary-search-tree-step-by-step-implementation-guide.webp" width="1200"/><media:title type="plain">Binary Search Tree: A Step-by-Step Implementation Guide for Developers</media:title><media:description type="plain">Dive deep into the Binary Search Tree: A Step-by-Step Implementation Guide. Learn its core concepts, operations, and practical applications for efficient dat...</media:description></entry><entry><title>Big O Notation Explained: A Beginner's Guide to Complexity</title><link href="https://analyticsdrive.tech/big-o-notation-explained-beginner-guide-complexity/" rel="alternate"/><published>2026-03-20T15:22:00+05:30</published><updated>2026-03-20T15:22:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-20:/big-o-notation-explained-beginner-guide-complexity/</id><summary type="html">&lt;p&gt;This comprehensive article offers Big O Notation Explained: A Beginner's Guide to Complexity, crucial for optimizing code and mastering algorithm analysis.&lt;/p&gt;</summary><content type="html">&lt;p&gt;In the dynamic world of software development, mastering the nuances of algorithmic &lt;strong&gt;complexity&lt;/strong&gt; is crucial, and understanding &lt;strong&gt;Big O Notation&lt;/strong&gt; serves as a fundamental &lt;strong&gt;guide&lt;/strong&gt; for every aspiring developer. In the realm of software development, where performance dictates user experience and resource efficiency drives scalability, understanding how our code performs under stress is paramount. It’s not enough for an algorithm to simply work; it must also perform efficiently, especially as input sizes grow. This is precisely where &lt;strong&gt;Big O Notation Explained: A Beginner's Guide to Complexity&lt;/strong&gt; becomes an indispensable tool. It provides a universal language to describe the performance characteristics of algorithms, helping developers analyze and compare their efficiency without getting bogged down in minute execution details. Grasping this concept is fundamental for any tech-savvy individual looking to deepen their understanding of efficient programming and algorithmic complexity.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-big-o-notation"&gt;What Is Big O Notation?&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#why-big-o-notation-matters"&gt;Why Big O Notation Matters&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-time-complexity-vs-space-complexity"&gt;Understanding Time Complexity vs. Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-big-o-notations-explained"&gt;Common Big O Notations Explained&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#o1-constant-time"&gt;O(1) – Constant Time&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#olog-n-logarithmic-time"&gt;O(log n) – Logarithmic Time&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#on-linear-time"&gt;O(n) – Linear Time&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#on-log-n-log-linear-time"&gt;O(n log n) – Log-Linear Time&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#on2-quadratic-time"&gt;O(n²) – Quadratic Time&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#o2n-exponential-time"&gt;O(2ⁿ) – Exponential Time&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#on-factorial-time"&gt;O(n!) – Factorial Time&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#dissecting-big-o-rules-and-simplification"&gt;Dissecting Big O: Rules and Simplification&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#rule-of-constants"&gt;Rule of Constants&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#rule-of-non-dominants"&gt;Rule of Non-Dominants&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#rule-of-addition-for-sequential-operations"&gt;Rule of Addition (for Sequential Operations)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#rule-of-multiplication-for-nested-operations"&gt;Rule of Multiplication (for Nested Operations)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-and-examples"&gt;Real-World Applications and Examples&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#searching-algorithms"&gt;Searching Algorithms&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#sorting-algorithms"&gt;Sorting Algorithms&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#data-structures"&gt;Data Structures&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#beyond-big-o-other-notations"&gt;Beyond Big O: Other Notations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#big-omega"&gt;Big Omega (Ω)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#big-theta"&gt;Big Theta (Θ)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-practical-impact-of-complexity-in-software-engineering"&gt;The Practical Impact of Complexity in Software Engineering&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-pitfalls-and-misconceptions"&gt;Common Pitfalls and Misconceptions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#mastering-big-o-for-interviews-and-beyond"&gt;Mastering Big O for Interviews and Beyond&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="what-is-big-o-notation"&gt;What Is Big O Notation?&lt;/h2&gt;
&lt;p&gt;Big O Notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. In computer science, it is primarily used to classify algorithms according to how their running time or space requirements grow as the input size grows. Think of it as a way to quantify the worst-case scenario for an algorithm's performance. It’s not concerned with the exact number of seconds an algorithm takes to run, but rather with the &lt;em&gt;rate&lt;/em&gt; at which its execution time or memory usage increases relative to the size of the input.&lt;/p&gt;
&lt;p&gt;To put it another way, Big O Notation gives us an upper bound on the growth rate of an algorithm's resource consumption. If an algorithm takes &lt;code&gt;f(n)&lt;/code&gt; operations to complete for an input of size &lt;code&gt;n&lt;/code&gt;, Big O Notation tells us something about &lt;code&gt;f(n)&lt;/code&gt; without needing to know the precise constant factors or lower-order terms that might be present. This abstraction is incredibly powerful because it allows us to compare algorithms theoretically, regardless of the specific hardware or programming language used.&lt;/p&gt;
&lt;h3 id="why-big-o-notation-matters"&gt;Why Big O Notation Matters&lt;/h3&gt;
&lt;p&gt;The practical implications of understanding Big O Notation are vast, touching every aspect of software engineering from system design to interview performance.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;1. Predicting Performance:&lt;/strong&gt;
    For small input sizes, differences in algorithmic efficiency might be negligible. However, as &lt;code&gt;n&lt;/code&gt; — the input size — scales up, the divergence in performance between an &lt;code&gt;O(n)&lt;/code&gt; algorithm and an &lt;code&gt;O(n²)&lt;/code&gt; algorithm becomes catastrophic. A developer who understands Big O can predict how their chosen algorithm will behave under heavy load, preventing bottlenecks before they even occur.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;2. Optimizing Code:&lt;/strong&gt;
    Knowing the complexity of different operations allows developers to make informed decisions about which algorithms to implement. If a particular section of code is identified as a bottleneck, understanding its Big O complexity helps in finding a more efficient alternative or refactoring the existing one. For instance, replacing a nested loop (&lt;code&gt;O(n²)&lt;/code&gt;) with a hash map lookup (&lt;code&gt;O(1)&lt;/code&gt; on average) can yield dramatic performance improvements. For a deeper understanding of how these efficient data structures work, you might want to read our article on &lt;a href="/hash-tables-deep-dive-how-they-work-use-cases/"&gt;Hash Tables: Deep Dive into Their Inner Workings &amp;amp; Use Cases&lt;/a&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;3. Informed Decision-Making:&lt;/strong&gt;
    When faced with multiple ways to solve a problem, Big O Notation provides a quantitative framework for comparing the efficiency of different approaches. This is crucial during design phases, where choices made about data structures and algorithms can have long-lasting impacts on the scalability and maintainability of a system.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;4. Communication and Collaboration:&lt;/strong&gt;
    Big O Notation offers a standardized vocabulary for discussing algorithm performance. When engineers talk about an algorithm being "logarithmic" or "linear," everyone understands the implications for its scalability. This streamlines technical discussions and facilitates better collaboration within development teams.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;5. Competitive Programming and Job Interviews:&lt;/strong&gt;
    Big O Notation is a cornerstone of competitive programming and almost every technical coding interview. Interviewers use it to gauge a candidate's analytical skills and their ability to write efficient, scalable code. Demonstrating a solid grasp of complexity analysis is often a prerequisite for roles in software development.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="understanding-time-complexity-vs-space-complexity"&gt;Understanding Time Complexity vs. Space Complexity&lt;/h3&gt;
&lt;p&gt;When discussing Big O Notation, we generally refer to two primary types of complexity: Time Complexity and Space Complexity. Both are critical for a holistic understanding of an algorithm's efficiency.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This refers to the amount of time an algorithm takes to run as a function of the input size &lt;code&gt;n&lt;/code&gt;. It's not about actual clock time (which varies with hardware, OS, and other factors), but rather about the number of elementary operations an algorithm performs. Elementary operations include comparisons, assignments, arithmetic operations, function calls, etc. We count these operations because they are assumed to take a constant amount of time.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This refers to the amount of memory (space) an algorithm requires to run as a function of the input size &lt;code&gt;n&lt;/code&gt;. This includes the memory used by the input itself (though often excluded when focusing on &lt;em&gt;auxiliary&lt;/em&gt; space complexity, which is the extra space the algorithm needs beyond the input) and any temporary variables, data structures, or recursion stack space. Just like time complexity, we're interested in how this memory usage grows with &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For example, an algorithm that creates a new array of the same size as its input &lt;code&gt;n&lt;/code&gt; would have &lt;code&gt;O(n)&lt;/code&gt; space complexity. An algorithm that only uses a few fixed variables regardless of input size would have &lt;code&gt;O(1)&lt;/code&gt; space complexity. Both time and space complexities are vital because an algorithm might be fast but consume too much memory, or vice versa. The goal is often to find a balance between the two.&lt;/p&gt;
&lt;h2 id="common-big-o-notations-explained"&gt;Common Big O Notations Explained&lt;/h2&gt;
&lt;p&gt;Understanding the most common Big O classifications is essential for analyzing and comparing algorithms effectively. Each classification describes a different growth rate, and recognizing these patterns is key to identifying efficient solutions.&lt;/p&gt;
&lt;h3 id="o1-constant-time"&gt;O(1) – Constant Time&lt;/h3&gt;
&lt;p&gt;An algorithm runs in &lt;code&gt;O(1)&lt;/code&gt; constant time if its execution time (or space usage) remains the same regardless of the input size. It performs a fixed number of operations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Imagine you need to get the first book from a bookshelf. It doesn't matter if the bookshelf has 10 books or 10,000 books; picking the first one always takes the same amount of time.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Accessing an element in an array by its index.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_first_element&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="c1"&gt;# get_first_element([1, 2, 3]) takes the same time as&lt;/span&gt;
&lt;span class="c1"&gt;# get_first_element([1, 2, 3, ..., 1000000])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="olog-n-logarithmic-time"&gt;O(log n) – Logarithmic Time&lt;/h3&gt;
&lt;p&gt;An algorithm runs in &lt;code&gt;O(log n)&lt;/code&gt; logarithmic time if its execution time grows proportionally to the logarithm of the input size. This often occurs when an algorithm effectively halves the problem space with each step.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Finding a word in a dictionary. You don't start from the beginning and check every word. Instead, you open to the middle, decide if your word is in the first or second half, and repeat the process. Each step significantly reduces the search space.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Binary search on a sorted array.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;binary_search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;low&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;low&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;
        &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;low&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;high&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="on-linear-time"&gt;O(n) – Linear Time&lt;/h3&gt;
&lt;p&gt;An algorithm runs in &lt;code&gt;O(n)&lt;/code&gt; linear time if its execution time grows directly proportional to the input size &lt;code&gt;n&lt;/code&gt;. If the input doubles, the execution time roughly doubles.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Reading every page of a book. If the book has 100 pages, it takes roughly twice as long as reading a 50-page book.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Iterating through all elements of an array to find a specific value (linear search) or sum all elements.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;sum_array_elements&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;total&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;element&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# This loop runs &amp;#39;n&amp;#39; times&lt;/span&gt;
        &lt;span class="n"&gt;total&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;element&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;total&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="on-log-n-log-linear-time"&gt;O(n log n) – Log-Linear Time&lt;/h3&gt;
&lt;p&gt;An algorithm runs in &lt;code&gt;O(n log n)&lt;/code&gt; log-linear time if its execution time grows proportionally to &lt;code&gt;n&lt;/code&gt; multiplied by the logarithm of &lt;code&gt;n&lt;/code&gt;. This is typically the performance of efficient sorting algorithms.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Sorting a deck of cards by repeatedly dividing it in half, sorting each half, and then merging them back together (like merge sort). The "n" comes from merging the halves, and "log n" comes from the repeated halving.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Merge sort or heapsort.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Conceptual overview of merge sort&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;merge_sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;

    &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
    &lt;span class="n"&gt;left_half&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[:&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;right_half&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;:]&lt;/span&gt;

    &lt;span class="n"&gt;left_sorted&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;merge_sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;left_half&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# log n recursive calls&lt;/span&gt;
    &lt;span class="n"&gt;right_sorted&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;merge_sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;right_half&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;merge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;left_sorted&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;right_sorted&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# n operations for merging&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="on2-quadratic-time"&gt;O(n²) – Quadratic Time&lt;/h3&gt;
&lt;p&gt;An algorithm runs in &lt;code&gt;O(n²)&lt;/code&gt; quadratic time if its execution time grows proportionally to the square of the input size &lt;code&gt;n&lt;/code&gt;. This often occurs with nested loops where each loop iterates over the input.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Imagine giving a handshake to everyone in a room. If there are &lt;code&gt;n&lt;/code&gt; people, each person needs to shake &lt;code&gt;n-1&lt;/code&gt; hands. The total handshakes would be approximately &lt;code&gt;n * n&lt;/code&gt;. If the number of people doubles, the number of handshakes quadruples.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Bubble sort, selection sort, or nested loops iterating over the same collection.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;bubble_sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;              &lt;span class="c1"&gt;# Outer loop runs &amp;#39;n&amp;#39; times&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="c1"&gt;# Inner loop runs &amp;#39;n&amp;#39; times in worst case&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="o2n-exponential-time"&gt;O(2ⁿ) – Exponential Time&lt;/h3&gt;
&lt;p&gt;An algorithm runs in &lt;code&gt;O(2ⁿ)&lt;/code&gt; exponential time if its execution time doubles with each additional element in the input. These algorithms are usually impractical for anything but very small input sizes.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The classic "grains of rice on a chessboard" problem. Placing one grain on the first square, two on the second, four on the third, and so on. The number of grains grows incredibly quickly.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Brute-force solutions to problems like the Traveling Salesperson Problem or finding all subsets of a set.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Recursive calculation of Fibonacci numbers without memoization&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Each call to &lt;code&gt;fibonacci(n)&lt;/code&gt; generates two more calls, roughly doubling the work for each increment of &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="on-factorial-time"&gt;O(n!) – Factorial Time&lt;/h3&gt;
&lt;p&gt;An algorithm runs in &lt;code&gt;O(n!)&lt;/code&gt; factorial time if its execution time grows proportionally to the factorial of the input size &lt;code&gt;n&lt;/code&gt;. These algorithms are extremely inefficient and become unmanageable even for very small &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you have &lt;code&gt;n&lt;/code&gt; different items and you want to find every possible way to arrange them (permutations). For 3 items, there are 3! = 6 arrangements. For 4 items, there are 4! = 24 arrangements. The growth is explosive.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Generating all permutations of a given set of elements using a naive approach.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;itertools&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;generate_permutations&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="c1"&gt;# This uses an optimized library function, but a naive recursive implementation&lt;/span&gt;
    &lt;span class="c1"&gt;# to generate all permutations would exhibit O(n!) complexity.&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;itertools&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;permutations&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;A direct recursive implementation of permutation generation would involve &lt;code&gt;n&lt;/code&gt; branches at the first level, &lt;code&gt;n-1&lt;/code&gt; at the second, and so on, leading to &lt;code&gt;n!&lt;/code&gt; operations.&lt;/p&gt;
&lt;h2 id="dissecting-big-o-rules-and-simplification"&gt;Dissecting Big O: Rules and Simplification&lt;/h2&gt;
&lt;p&gt;When analyzing algorithms, you often end up with complex functions describing the number of operations. Big O Notation simplifies these functions by focusing on the dominant term and ignoring constants. This simplification is based on a few fundamental rules.&lt;/p&gt;
&lt;h3 id="rule-of-constants"&gt;Rule of Constants&lt;/h3&gt;
&lt;p&gt;Constants are dropped. If an algorithm performs &lt;code&gt;3n&lt;/code&gt; operations or &lt;code&gt;100n&lt;/code&gt; operations, both are considered &lt;code&gt;O(n)&lt;/code&gt;. The reason is that as &lt;code&gt;n&lt;/code&gt; becomes very large, the constant factor becomes less significant compared to the growth rate of &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;print_twice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# n operations&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# another n operations&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# This is O(n + n) = O(2n), which simplifies to O(n).&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;While &lt;code&gt;2n&lt;/code&gt; is technically twice as much work as &lt;code&gt;n&lt;/code&gt;, their &lt;em&gt;growth rate&lt;/em&gt; is the same: linear. When &lt;code&gt;n&lt;/code&gt; approaches infinity, the &lt;code&gt;2&lt;/code&gt; becomes trivial.&lt;/p&gt;
&lt;h3 id="rule-of-non-dominants"&gt;Rule of Non-Dominants&lt;/h3&gt;
&lt;p&gt;Lower-order terms are dropped. When a function includes multiple terms with different growth rates (e.g., &lt;code&gt;n² + n&lt;/code&gt;), the term with the highest growth rate dominates as &lt;code&gt;n&lt;/code&gt; gets large. Therefore, &lt;code&gt;O(n² + n)&lt;/code&gt; simplifies to &lt;code&gt;O(n²)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;quadratic_and_linear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;          &lt;span class="c1"&gt;# O(n^2) part&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;          &lt;span class="c1"&gt;# O(n) part&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;span class="c1"&gt;# This is O(n^2 + n), which simplifies to O(n^2).&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;As &lt;code&gt;n&lt;/code&gt; grows, &lt;code&gt;n²&lt;/code&gt; grows much, much faster than &lt;code&gt;n&lt;/code&gt;. For &lt;code&gt;n=1000&lt;/code&gt;, &lt;code&gt;n²&lt;/code&gt; is &lt;code&gt;1,000,000&lt;/code&gt; while &lt;code&gt;n&lt;/code&gt; is &lt;code&gt;1,000&lt;/code&gt;. The &lt;code&gt;n²&lt;/code&gt; term completely overshadows &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="rule-of-addition-for-sequential-operations"&gt;Rule of Addition (for Sequential Operations)&lt;/h3&gt;
&lt;p&gt;When an algorithm performs a sequence of operations, where one operation is followed by another, their complexities are added. If the first operation has complexity &lt;code&gt;O(A)&lt;/code&gt; and the second has complexity &lt;code&gt;O(B)&lt;/code&gt;, the total complexity is &lt;code&gt;O(A + B)&lt;/code&gt;. Then, apply the rule of non-dominants to simplify.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If an algorithm first sorts an array (&lt;code&gt;O(n log n)&lt;/code&gt;) and then iterates through it (&lt;code&gt;O(n)&lt;/code&gt;), the total complexity is &lt;code&gt;O(n log n + n)&lt;/code&gt;. By the rule of non-dominants, this simplifies to &lt;code&gt;O(n log n)&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="rule-of-multiplication-for-nested-operations"&gt;Rule of Multiplication (for Nested Operations)&lt;/h3&gt;
&lt;p&gt;When operations are nested (e.g., a loop inside another loop), their complexities are multiplied. If an outer loop runs &lt;code&gt;A&lt;/code&gt; times and an inner loop runs &lt;code&gt;B&lt;/code&gt; times for each iteration of the outer loop, the total complexity is &lt;code&gt;O(A * B)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;nested_loops&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;arr2&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;arr1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# O(len(arr1)) iterations&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;arr2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# O(len(arr2)) iterations&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# If len(arr1) is &amp;#39;n&amp;#39; and len(arr2) is &amp;#39;m&amp;#39;, this is O(n * m).&lt;/span&gt;
&lt;span class="c1"&gt;# If both are &amp;#39;n&amp;#39;, it&amp;#39;s O(n * n) = O(n^2).&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This rule explains why nested loops often lead to quadratic or higher complexities.&lt;/p&gt;
&lt;h2 id="real-world-applications-and-examples"&gt;Real-World Applications and Examples&lt;/h2&gt;
&lt;p&gt;Big O Notation isn't just a theoretical concept; it has profound practical implications for building scalable and efficient software systems. Let's look at how it applies to common algorithmic patterns and data structures.&lt;/p&gt;
&lt;h3 id="searching-algorithms"&gt;Searching Algorithms&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Linear Search:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;
    Iterates through each element of a list sequentially until the target is found or the list ends.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;
    &lt;code&gt;O(n)&lt;/code&gt; in the worst case (target is at the end or not present).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Application:&lt;/strong&gt;
    Simple lists, unsorted data.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Binary Search:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;
    For a sorted list, it repeatedly divides the search interval in half.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;
    &lt;code&gt;O(log n)&lt;/code&gt; in the worst case.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Application:&lt;/strong&gt;
    Databases, dictionaries, efficiently searching large sorted datasets. This vastly superior complexity compared to linear search for large datasets highlights the importance of data being sorted.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="sorting-algorithms"&gt;Sorting Algorithms&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Bubble Sort / Selection Sort / Insertion Sort:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;
    Simple comparison-based sorts.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;
    &lt;code&gt;O(n²)&lt;/code&gt; in the worst and average cases.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Application:&lt;/strong&gt;
    Primarily for educational purposes or extremely small lists where simplicity outweighs efficiency concerns. Rarely used in production for large datasets.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Merge Sort / Heap Sort:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;
    More advanced comparison-based sorts using divide-and-conquer or heap data structures.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;
    &lt;code&gt;O(n log n)&lt;/code&gt; in the worst and average cases.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Application:&lt;/strong&gt;
    Widely used in general-purpose sorting libraries (e.g., Python's &lt;code&gt;sort()&lt;/code&gt; method or Java's &lt;code&gt;Arrays.sort()&lt;/code&gt; use variations of merge sort or Timsort, which is &lt;code&gt;O(n log n)&lt;/code&gt;). These are efficient for large datasets.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Quick Sort:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;
    A popular divide-and-conquer sort that picks an element as a pivot and partitions the array around the pivot.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;
    &lt;code&gt;O(n log n)&lt;/code&gt; on average, but &lt;code&gt;O(n²)&lt;/code&gt; in the worst case (though careful pivot selection usually mitigates this).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Application:&lt;/strong&gt;
    Also widely used in general-purpose sorting libraries due to its good average-case performance and in-place sorting capabilities (for some implementations). To explore the QuickSort algorithm in detail, refer to our comprehensive guide: &lt;a href="/quicksort-algorithm-explained-step-by-step-guide/"&gt;QuickSort Algorithm Explained: A Step-by-Step Guide for Developers&lt;/a&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="data-structures"&gt;Data Structures&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Arrays/Lists:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Access by index:&lt;/strong&gt;
    &lt;code&gt;O(1)&lt;/code&gt; – direct memory access.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion/Deletion (at end):&lt;/strong&gt;
    &lt;code&gt;O(1)&lt;/code&gt; (amortized) – may involve resizing.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion/Deletion (at beginning/middle):&lt;/strong&gt;
    &lt;code&gt;O(n)&lt;/code&gt; – requires shifting subsequent elements.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Searching (unsorted):&lt;/strong&gt;
    &lt;code&gt;O(n)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Searching (sorted, with binary search):&lt;/strong&gt;
    &lt;code&gt;O(log n)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Linked Lists:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Access by index:&lt;/strong&gt;
    &lt;code&gt;O(n)&lt;/code&gt; – must traverse from the beginning.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion/Deletion (at beginning):&lt;/strong&gt;
    &lt;code&gt;O(1)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion/Deletion (at specific position, after finding it):&lt;/strong&gt;
    &lt;code&gt;O(1)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Searching:&lt;/strong&gt;
    &lt;code&gt;O(n)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Application:&lt;/strong&gt;
    When frequent insertions/deletions at ends or known positions are needed, and random access is less critical.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Hash Tables (Hash Maps/Dictionaries):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion/Deletion/Access:&lt;/strong&gt;
    &lt;code&gt;O(1)&lt;/code&gt; on average – assuming a good hash function and minimal collisions. &lt;code&gt;O(n)&lt;/code&gt; in the worst case (e.g., all elements hash to the same bucket).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Application:&lt;/strong&gt;
    Extremely fast lookups, caches, symbol tables, frequency counters. Their average &lt;code&gt;O(1)&lt;/code&gt; performance makes them highly desirable for many applications.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Trees (e.g., Binary Search Trees - BSTs):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Insertion/Deletion/Searching:&lt;/strong&gt;
    &lt;code&gt;O(h)&lt;/code&gt; where &lt;code&gt;h&lt;/code&gt; is the height of the tree. For a balanced BST (like AVL trees or Red-Black trees), &lt;code&gt;h = log n&lt;/code&gt;, so &lt;code&gt;O(log n)&lt;/code&gt;. For a skewed (unbalanced) BST, &lt;code&gt;h = n&lt;/code&gt;, so &lt;code&gt;O(n)&lt;/code&gt;. For a deeper dive into tree structures and their operations, check out our guide on &lt;a href="/demystifying-binary-trees-structure-traversal-use/"&gt;Demystifying Binary Trees: Structure, Traversal, &amp;amp; Use Explained&lt;/a&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Application:&lt;/strong&gt;
    Hierarchical data, efficient searching, maintaining sorted data, database indexing. Self-balancing BSTs guarantee &lt;code&gt;O(log n)&lt;/code&gt; performance.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Graphs (e.g., Adjacency List/Matrix):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Adding/removing vertex:&lt;/strong&gt;
    &lt;code&gt;O(1)&lt;/code&gt; for adjacency list, &lt;code&gt;O(V)&lt;/code&gt; for adjacency matrix (where &lt;code&gt;V&lt;/code&gt; is number of vertices).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Adding/removing edge:&lt;/strong&gt;
    &lt;code&gt;O(1)&lt;/code&gt; for adjacency list, &lt;code&gt;O(1)&lt;/code&gt; for adjacency matrix.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Checking if edge exists:&lt;/strong&gt;
    &lt;code&gt;O(degree(u))&lt;/code&gt; for adjacency list (if checking if &lt;code&gt;v&lt;/code&gt; is neighbor of &lt;code&gt;u&lt;/code&gt;), &lt;code&gt;O(1)&lt;/code&gt; for adjacency matrix.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Traversals (BFS/DFS):&lt;/strong&gt;
    &lt;code&gt;O(V + E)&lt;/code&gt; where &lt;code&gt;E&lt;/code&gt; is number of edges (for adjacency list), or &lt;code&gt;O(V²)&lt;/code&gt;(for adjacency matrix).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Application:&lt;/strong&gt;
    Social networks, routing algorithms, network analysis, relationship modeling.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The choice of data structure directly impacts the Big O complexity of operations performed on the data, which in turn affects the overall efficiency of an algorithm.&lt;/p&gt;
&lt;h2 id="beyond-big-o-other-notations"&gt;Beyond Big O: Other Notations&lt;/h2&gt;
&lt;p&gt;While Big O Notation is the most common and widely used for describing the upper bound (worst-case scenario) of an algorithm's performance, two other related notations provide a more complete picture of an algorithm's behavior: Big Omega (Ω) and Big Theta (Θ). Understanding these can offer a more nuanced analysis.&lt;/p&gt;
&lt;h3 id="big-omega"&gt;Big Omega (Ω)&lt;/h3&gt;
&lt;p&gt;Big Omega Notation describes the &lt;strong&gt;lower bound&lt;/strong&gt; of an algorithm's running time. It represents the best-case scenario for an algorithm. If an algorithm's time complexity is &lt;code&gt;Ω(g(n))&lt;/code&gt;, it means that for sufficiently large &lt;code&gt;n&lt;/code&gt;, the running time will be at least &lt;code&gt;C * g(n)&lt;/code&gt; for some constant &lt;code&gt;C&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you say "it will take at least 5 minutes to walk to the store," you're giving a lower bound. It might take longer, but it definitely won't be less than 5 minutes.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Linear Search:&lt;/strong&gt; In the best case, the target element is the very first one in the array. This takes a constant number of operations. So, linear search has &lt;code&gt;Ω(1)&lt;/code&gt; complexity.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sorting Algorithms:&lt;/strong&gt; Any comparison-based sorting algorithm must at least look at every element, so its best-case (and lower bound) complexity is &lt;code&gt;Ω(n)&lt;/code&gt;. Even if the array is already sorted, you typically have to iterate through it once to confirm it's sorted.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Big Omega is less frequently used in practical analysis than Big O because developers are usually more concerned with the worst-case performance to ensure reliability.&lt;/p&gt;
&lt;h3 id="big-theta"&gt;Big Theta (Θ)&lt;/h3&gt;
&lt;p&gt;Big Theta Notation describes the &lt;strong&gt;tight bound&lt;/strong&gt; of an algorithm's running time. It specifies both an upper bound and a lower bound for the algorithm's performance. If an algorithm's time complexity is &lt;code&gt;Θ(g(n))&lt;/code&gt;, it means that for sufficiently large &lt;code&gt;n&lt;/code&gt;, the running time will be both &lt;code&gt;O(g(n))&lt;/code&gt; and &lt;code&gt;Ω(g(n))&lt;/code&gt;. In essence, the algorithm's running time grows &lt;em&gt;exactly&lt;/em&gt; as &lt;code&gt;g(n)&lt;/code&gt; for large &lt;code&gt;n&lt;/code&gt;, ignoring constant factors.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you say "it will take exactly 10 minutes to walk to the store," you're giving a tight bound. It won't be less, and it won't be more, for practical purposes.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Accessing an array element by index:&lt;/strong&gt; This operation always takes a constant amount of time, regardless of the array size. So, it is &lt;code&gt;Θ(1)&lt;/code&gt;. Its best-case is &lt;code&gt;O(1)&lt;/code&gt;, and its worst-case is &lt;code&gt;O(1)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Summing all elements in an array:&lt;/strong&gt; This always involves iterating through &lt;code&gt;n&lt;/code&gt; elements. Its lower bound is &lt;code&gt;Ω(n)&lt;/code&gt; and its upper bound is &lt;code&gt;O(n)&lt;/code&gt;. Therefore, its tight bound is &lt;code&gt;Θ(n)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Big Theta is used when the best-case and worst-case complexities are asymptotically the same. It provides a more precise statement of an algorithm's growth rate when its performance doesn't fluctuate wildly between different input arrangements.&lt;/p&gt;
&lt;h2 id="the-practical-impact-of-complexity-in-software-engineering"&gt;The Practical Impact of Complexity in Software Engineering&lt;/h2&gt;
&lt;p&gt;The theoretical elegance of Big O Notation translates directly into tangible benefits and critical considerations in the daily life of a software engineer. Its influence spans across development lifecycle stages, impacting everything from initial design to long-term maintenance.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Scalability and Performance Bottlenecks:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Modern applications often deal with vast amounts of data and millions of users. A seemingly minor &lt;code&gt;O(n²)&lt;/code&gt; operation, if executed frequently or on a growing dataset, can quickly become a performance bottleneck. For instance, processing user recommendations in a social media app with &lt;code&gt;O(n²)&lt;/code&gt; logic would collapse if &lt;code&gt;n&lt;/code&gt; represents millions of users, whereas an &lt;code&gt;O(n log n)&lt;/code&gt; or &lt;code&gt;O(n)&lt;/code&gt; approach might scale effortlessly. Understanding Big O allows engineers to proactively identify and mitigate these risks during system design, ensuring that the software can handle increasing loads without degrading user experience.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Resource Utilization (CPU &amp;amp; Memory):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Time complexity directly relates to CPU cycles, while space complexity relates to memory usage. In environments where resources are constrained (e.g., embedded systems, mobile apps, serverless functions with limited memory), optimizing both is paramount. An algorithm with high space complexity, for example, might lead to memory leaks or excessive paging, slowing down the entire system or incurring higher cloud costs. A careful analysis of Big O helps in selecting algorithms that are efficient not just in time but also in memory footprint.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;System Design and Architecture:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The choice of data structures and algorithms is foundational to system architecture. Database indexing, caching strategies, search engine ranking, and real-time data processing all rely heavily on algorithms with optimal Big O characteristics. For example, a search engine heavily depends on &lt;code&gt;O(log n)&lt;/code&gt; or &lt;code&gt;O(1)&lt;/code&gt; average-time lookups (using hash tables or balanced trees) to respond quickly to user queries over billions of documents. Designing a system without considering the Big O of its core components is akin to building a house without a strong foundation – it will eventually crumble under stress.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Cost Implications:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;For cloud-native applications, inefficient algorithms can lead to higher operational costs. More CPU cycles mean more compute time, and higher memory usage means more expensive instances or storage. Optimizing complexity can directly translate into significant cost savings for businesses running large-scale infrastructure.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Maintainability and Refactoring:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Code written with performance considerations in mind tends to be more robust and easier to maintain. When refactoring an existing system, knowing the Big O of the current implementation allows engineers to justify the effort required for optimization, setting clear performance targets for the new solution. It also helps in understanding the impact of changes – accidentally introducing an &lt;code&gt;O(n!)&lt;/code&gt; operation into a critical path could be disastrous.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;User Experience:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Ultimately, all these technical considerations boil down to user experience. Slow applications frustrate users, leading to abandonment. Fast, responsive applications enhance engagement and satisfaction. Big O Notation is a critical tool in an engineer's arsenal to deliver performant software that delights its users.&lt;/p&gt;
&lt;h2 id="common-pitfalls-and-misconceptions"&gt;Common Pitfalls and Misconceptions&lt;/h2&gt;
&lt;p&gt;Despite its fundamental importance, Big O Notation is often subject to misunderstandings that can lead to suboptimal decisions or incorrect analysis.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Ignoring Small Input Sizes:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Big O describes asymptotic behavior, meaning how an algorithm performs as &lt;code&gt;n&lt;/code&gt; approaches infinity. For very small &lt;code&gt;n&lt;/code&gt;, an algorithm with a higher Big O (e.g., &lt;code&gt;O(n²)&lt;/code&gt;) might actually perform faster than one with a lower Big O (e.g., &lt;code&gt;O(n log n)&lt;/code&gt;) due to smaller constant factors, less overhead, or simpler implementation. For example, bubble sort (&lt;code&gt;O(n²)&lt;/code&gt;) can be faster than merge sort (&lt;code&gt;O(n log n)&lt;/code&gt;) for an array of 5 elements because merge sort has more setup overhead.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Focusing Too Much on Best Case:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;While Big Omega exists, practically, engineers are usually most concerned with the worst-case scenario (Big O). Relying on best-case performance for critical systems is risky because real-world inputs often hit the worst case, leading to unexpected slowdowns. A prime example is Quick Sort, which is &lt;code&gt;O(n log n)&lt;/code&gt; on average but &lt;code&gt;O(n²)&lt;/code&gt; in its worst case. For robust systems, careful implementation to avoid the worst case or choosing an algorithm with a guaranteed &lt;code&gt;O(n log n)&lt;/code&gt; worst case (like Merge Sort) is crucial.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Confusing Big O with Actual Speed:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Big O Notation is about &lt;em&gt;growth rate&lt;/em&gt;, not absolute speed. An &lt;code&gt;O(n)&lt;/code&gt; algorithm might take longer than an &lt;code&gt;O(n²)&lt;/code&gt; algorithm if the constant factor for &lt;code&gt;O(n)&lt;/code&gt; is extremely large and &lt;code&gt;n&lt;/code&gt; is relatively small.
For instance, &lt;code&gt;f(n) = 1000n&lt;/code&gt; (O(n)) vs. &lt;code&gt;g(n) = n^2&lt;/code&gt; (O(n^2)). For &lt;code&gt;n=10&lt;/code&gt;, &lt;code&gt;f(n)=10000&lt;/code&gt; and &lt;code&gt;g(n)=100&lt;/code&gt;. Here &lt;code&gt;g(n)&lt;/code&gt; is faster. Only as &lt;code&gt;n&lt;/code&gt; grows much larger (e.g., &lt;code&gt;n=2000&lt;/code&gt;, &lt;code&gt;f(n)=2000000&lt;/code&gt;, &lt;code&gt;g(n)=4000000&lt;/code&gt;), does the true asymptotic behavior assert itself.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;4. Not Differentiating Between Average and Worst-Case:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Some algorithms have different complexities for their average-case and worst-case scenarios. Hash tables, for example, offer &lt;code&gt;O(1)&lt;/code&gt; average-case lookups but can degrade to &lt;code&gt;O(n)&lt;/code&gt; in the worst case (due to collisions). It's crucial to understand these distinctions, especially in security-sensitive or performance-critical applications where worst-case performance could be exploited or cause system failure.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;5. Forgetting About Space Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;While time complexity often takes center stage, space complexity is equally important. An algorithm that is very fast but consumes excessive memory might not be viable in environments with limited resources, such as embedded systems or mobile devices. Recursion, for instance, can lead to &lt;code&gt;O(n)&lt;/code&gt; space complexity due to the call stack depth, which can be problematic for deep recursion.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;6. Misinterpreting &lt;code&gt;n&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;n&lt;/code&gt; in Big O Notation represents the "size of the input." It's critical to correctly define what &lt;code&gt;n&lt;/code&gt; refers to for a given problem. Is it the number of items in a list? The number of bits in an integer? The number of vertices or edges in a graph? Misidentifying &lt;code&gt;n&lt;/code&gt; will lead to an incorrect complexity analysis.&lt;/p&gt;
&lt;p&gt;Avoiding these common pitfalls requires not just memorizing the Big O categories but genuinely understanding the underlying principles and their practical implications.&lt;/p&gt;
&lt;h2 id="mastering-big-o-for-interviews-and-beyond"&gt;Mastering Big O for Interviews and Beyond&lt;/h2&gt;
&lt;p&gt;Mastering Big O Notation is not merely an academic exercise; it's a critical skill that sets apart competent developers. For technical interviews, it's virtually guaranteed that you'll be asked to analyze the time and space complexity of your solutions. Beyond interviews, a deep understanding of Big O enables you to design, implement, and maintain high-performance, scalable software.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;For Interviews:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Understand the Basics Thoroughly:&lt;/strong&gt;
    Be able to explain O(1), O(log n), O(n), O(n log n), O(n²), and O(2ⁿ) with simple examples.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Practice Complexity Analysis:&lt;/strong&gt;
    For every algorithm you study or implement, make it a habit to determine its time and space complexity. This is the most crucial step.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Loops:&lt;/strong&gt; A single loop iterating &lt;code&gt;n&lt;/code&gt; times is &lt;code&gt;O(n)&lt;/code&gt;. Nested loops often lead to &lt;code&gt;O(n²)&lt;/code&gt;, &lt;code&gt;O(n³)&lt;/code&gt;, etc.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursion:&lt;/strong&gt; Analyze the depth of the recursion stack and the work done at each level.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Structure Operations:&lt;/strong&gt; Know the Big O of common operations (insertion, deletion, lookup) for arrays, linked lists, hash maps, trees, and graphs.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Identify &lt;code&gt;n&lt;/code&gt;:&lt;/strong&gt;
    Clearly define what &lt;code&gt;n&lt;/code&gt; represents in the context of the problem. Is it the number of elements, the length of a string, or something else?&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Simplify Aggressively:&lt;/strong&gt;
    Remember the rules: drop constants and non-dominant terms. &lt;code&gt;O(2n + 5)&lt;/code&gt; is &lt;code&gt;O(n)&lt;/code&gt;. &lt;code&gt;O(n² + n log n)&lt;/code&gt; is &lt;code&gt;O(n²)&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Discuss Trade-offs:&lt;/strong&gt;
    Be prepared to discuss the trade-offs between different solutions (e.g., a faster algorithm might use more memory, or a simpler one might be slower). Interviewers love to hear this kind of nuanced thinking.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Analyze Both Time and Space:&lt;/strong&gt;
    Don't forget space complexity! Many candidates focus solely on time complexity.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Beyond Interviews:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Design Decisions:&lt;/strong&gt;
    Apply Big O analysis when choosing data structures and algorithms during system design. For example, if you need fast lookups for a large dataset, a hash map or balanced tree is likely superior to a linear list.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Performance Tuning:&lt;/strong&gt;
    Use Big O to pinpoint performance bottlenecks in existing codebases. Tools like profilers can show you where your code spends the most time, but Big O helps explain &lt;em&gt;why&lt;/em&gt; and guides you towards more efficient alternatives.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Code Reviews:&lt;/strong&gt;
    Critique others' code (and your own) for efficiency. Suggest improvements based on complexity analysis.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Staying Current:&lt;/strong&gt;
    As new algorithms and data structures emerge, Big O provides the framework to understand their performance characteristics and evaluate their suitability for various problems.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;By consistently applying Big O Notation in your learning and daily work, you'll not only ace your interviews but also become a more effective and insightful software engineer, capable of building robust, scalable, and high-performance applications.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Understanding Big O Notation is far more than a theoretical exercise; it's a foundational skill for anyone serious about building efficient, scalable software. This &lt;strong&gt;Big O Notation Explained: A Beginner's Guide to Complexity&lt;/strong&gt; has traversed its core definitions, practical importance, common classifications, and the rules governing its simplification. We've explored how it quantifies both time and space complexity, illustrated its application across various algorithms and data structures, and distinguished it from related notations like Big Omega and Big Theta. The practical impact on software engineering, from predicting performance to optimizing resource utilization and informing system design, cannot be overstated. By internalizing these concepts and avoiding common pitfalls, developers can write code that not only works but performs optimally, ensuring robust systems that scale with future demands. Master Big O, and you master a crucial aspect of software excellence.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: Why is Big O Notation important?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Big O Notation is crucial for predicting how an algorithm's performance scales with input size, helping developers choose efficient solutions, optimize code, and prevent performance bottlenecks in large-scale systems. It provides a standardized way to communicate algorithm efficiency.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What's the difference between Big O, Big Omega, and Big Theta?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Big O (O) describes the worst-case (upper bound) performance, Big Omega (Ω) describes the best-case (lower bound), and Big Theta (Θ) describes the tight or exact bound when best and worst cases are asymptotically the same. Developers typically focus on Big O for reliability.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Does Big O Notation measure actual execution time?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: No, Big O Notation does not measure actual execution time in seconds. Instead, it describes the &lt;em&gt;growth rate&lt;/em&gt; of an algorithm's running time or space requirements as the input size increases, focusing on the number of operations rather than absolute speed, which can vary by hardware and programming language.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/analysis-of-algorithms-set-1-introduction/"&gt;GeeksforGeeks: Analysis of Algorithms | Set 1 (Introduction to Asymptotic Analysis)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.bigocheatsheet.com/"&gt;Big O Cheatsheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=J_NF_iV7B1Q"&gt;Harvard CS50: Asymptotic Notation (Video Lecture)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation"&gt;Khan Academy: Algorithm analysis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://mitpress.mit.edu/books/introduction-algorithms"&gt;Introduction to Algorithms (CLRS) - The classic textbook for in-depth algorithmic analysis.&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Competitive Programming"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/big-o-notation-explained-beginner-guide-complexity.webp" width="1200"/><media:title type="plain">Big O Notation Explained: A Beginner's Guide to Complexity</media:title><media:description type="plain">This comprehensive article offers Big O Notation Explained: A Beginner's Guide to Complexity, crucial for optimizing code and mastering algorithm analysis.</media:description></entry><entry><title>Hash Tables: Deep Dive into Their Inner Workings &amp; Use Cases</title><link href="https://analyticsdrive.tech/hash-tables-deep-dive-how-they-work-use-cases/" rel="alternate"/><published>2026-03-19T10:57:00+05:30</published><updated>2026-03-19T10:57:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-19:/hash-tables-deep-dive-how-they-work-use-cases/</id><summary type="html">&lt;p&gt;Unlock the power of Hash Tables: Deep Dive into How They Work &amp;amp; Use Cases. Explore their O(1) efficiency, essential components, and widespread applications i...&lt;/p&gt;</summary><content type="html">&lt;p&gt;In the realm of computer science and software engineering, few data structures are as fundamental and ubiquitous as hash tables. These powerful constructs are the unsung heroes behind countless applications, from database indexing to caching systems, offering unparalleled speed for data retrieval, insertion, and deletion. This article promises a comprehensive &lt;strong&gt;Hash Tables: Deep Dive into How They Work &amp;amp; Use Cases&lt;/strong&gt;, exploring their intricate internal mechanisms, critical components, and the myriad ways they underpin modern technology. We'll delve into their remarkable efficiency, their inherent challenges, and their indispensable role in shaping the software landscape. Prepare to embark on a journey that unravels the &lt;strong&gt;inner workings&lt;/strong&gt; of one of computing's most vital &lt;strong&gt;use cases&lt;/strong&gt; for data management.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-exactly-are-hash-tables-a-foundational-understanding"&gt;What Exactly Are Hash Tables? A Foundational Understanding&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#hash-tables-deep-dive-into-their-core-mechanics"&gt;Hash Tables: Deep Dive into Their Core Mechanics&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-hash-function-the-brain-of-the-operation"&gt;The Hash Function: The Brain of the Operation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-array-or-buckets-where-data-lives"&gt;The Array (or Buckets): Where Data Lives&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#collision-resolution-handling-the-inevitable"&gt;Collision Resolution: Handling the Inevitable&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#separate-chaining"&gt;Separate Chaining&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#open-addressing"&gt;Open Addressing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#key-performance-indicators-time-complexity-space"&gt;Key Performance Indicators: Time Complexity &amp;amp; Space&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-load-factor-a-critical-tuning-parameter"&gt;The Load Factor: A Critical Tuning Parameter&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#impact-on-performance"&gt;Impact on Performance&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#resizing-and-rehashing"&gt;Resizing and Rehashing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-use-cases-of-hash-tables"&gt;Real-World Use Cases of Hash Tables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#advantages-of-hash-tables"&gt;Advantages of Hash Tables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#disadvantages-and-challenges"&gt;Disadvantages and Challenges&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#optimizing-hash-table-performance"&gt;Optimizing Hash Table Performance&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#choosing-a-good-hash-function"&gt;Choosing a Good Hash Function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#managing-load-factor-and-resizing-strategy"&gt;Managing Load Factor and Resizing Strategy&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#selecting-the-right-collision-resolution-strategy"&gt;Selecting the Right Collision Resolution Strategy&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#using-specialized-hash-table-variants"&gt;Using Specialized Hash Table Variants&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#beyond-the-basics-advanced-concepts-variations"&gt;Beyond the Basics: Advanced Concepts &amp;amp; Variations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#cuckoo-hashing"&gt;Cuckoo Hashing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#extendible-hashing"&gt;Extendible Hashing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#consistent-hashing"&gt;Consistent Hashing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-future-landscape-hash-tables-in-emerging-tech"&gt;The Future Landscape: Hash Tables in Emerging Tech&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id="what-exactly-are-hash-tables-a-foundational-understanding"&gt;What Exactly Are Hash Tables? A Foundational Understanding&lt;/h2&gt;
&lt;p&gt;Imagine you're in a vast library, and you need to find a specific book. Instead of scanning every shelf, you'd likely consult a catalog that tells you exactly where to go. A hash table operates on a remarkably similar principle. At its core, a hash table is a data structure that implements an associative array abstract data type, mapping keys to values. It's like a dictionary or a phone book: you provide a "key" (e.g., a word, a person's name), and it quickly gives you the associated "value" (e.g., its definition, their phone number).&lt;/p&gt;
&lt;p&gt;Unlike arrays, which rely on numerical indices for direct access, or linked lists, which require sequential traversal, hash tables use a special function—a hash function—to transform a key into an index within an underlying array. This transformation allows for incredibly fast lookups, insertions, and deletions, typically achieving an average time complexity of O(1), often referred to as constant time. This efficiency is a game-changer for applications demanding rapid access to large datasets, making hash tables a cornerstone of high-performance computing. They provide a dynamic and efficient way to store and retrieve data, outperforming many other data structures for specific operations. For instance, while other structures like &lt;a href="/demystifying-binary-trees-structure-traversal-use/"&gt;Binary Trees&lt;/a&gt; are powerful for ordered data, hash tables excel at direct, unordered access.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="hash-tables-deep-dive-into-their-core-mechanics"&gt;Hash Tables: Deep Dive into Their Core Mechanics&lt;/h2&gt;
&lt;p&gt;To truly appreciate the power of hash tables, it's essential to understand their internal mechanics. Their magic lies in a clever interplay between a hash function, an array of buckets, and a strategy for handling collisions. Let's break down each component.&lt;/p&gt;
&lt;h3 id="the-hash-function-the-brain-of-the-operation"&gt;The Hash Function: The Brain of the Operation&lt;/h3&gt;
&lt;p&gt;The hash function is arguably the most critical component of a hash table. Its job is to take an input key (which can be any data type – a string, an object, an integer) and convert it into a numerical index that corresponds to a specific slot or "bucket" in the underlying array.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Characteristics of a Good Hash Function:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Determinism:&lt;/strong&gt; For the same input key, the hash function must always produce the same output hash code. This ensures consistency in data storage and retrieval.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Uniform Distribution:&lt;/strong&gt; A good hash function should distribute keys as evenly as possible across the entire range of available array indices. This minimizes collisions, which are instances where different keys hash to the same index.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficiency:&lt;/strong&gt; The hash function itself must be computationally fast. If calculating the hash takes too long, it negates the speed benefits of the hash table.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sensitivity to Key Differences:&lt;/strong&gt; Even a slight change in the input key should ideally result in a significantly different hash code. This helps spread keys out more effectively.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Example Hash Functions:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;For integer keys, a simple modulo operation is often used: &lt;code&gt;index = key % array_size&lt;/code&gt;. For string keys, more sophisticated algorithms are required. A common approach involves polynomial rolling hash functions, which treat the string as a polynomial and evaluate it at a specific prime number, then take the result modulo the array size.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Role of Key Type:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The design of the hash function is highly dependent on the type of key it will process. A hash function for integer keys will differ significantly from one designed for string keys, floating-point numbers, or custom objects. For custom objects, programmers often need to override default hash functions (e.g., &lt;code&gt;hashCode()&lt;/code&gt; in Java or &lt;code&gt;__hash__()&lt;/code&gt; in Python) to ensure they produce unique and well-distributed hash codes based on the object's significant attributes. Failing to implement a proper hash function for custom objects can lead to poor performance and incorrect behavior.&lt;/p&gt;
&lt;h3 id="the-array-or-buckets-where-data-lives"&gt;The Array (or Buckets): Where Data Lives&lt;/h3&gt;
&lt;p&gt;Beneath the abstract concept of a hash table lies a simple, contiguous block of memory: an array. This array is divided into "slots" or "buckets," each capable of holding one or more key-value pairs. When the hash function generates an index, it points to one of these buckets.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conceptual Structure:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Imagine an array of empty containers. When you insert a key-value pair, the hash function tells you which container to put it in. When you look up a key, the hash function tells you which container to check. The size of this array directly impacts the performance and efficiency of the hash table. A larger array can reduce the chances of collisions, but it also consumes more memory. Conversely, a smaller array saves memory but increases the likelihood of collisions, potentially degrading performance.&lt;/p&gt;
&lt;h3 id="collision-resolution-handling-the-inevitable"&gt;Collision Resolution: Handling the Inevitable&lt;/h3&gt;
&lt;p&gt;No matter how good a hash function is, it's almost impossible to completely avoid collisions, especially as more data is added. A collision occurs when two different keys hash to the same index in the array. Since two distinct key-value pairs cannot occupy the exact same memory location, hash tables employ various strategies to resolve these conflicts. The choice of collision resolution strategy significantly impacts the hash table's performance, particularly in worst-case scenarios.&lt;/p&gt;
&lt;h4 id="separate-chaining"&gt;Separate Chaining&lt;/h4&gt;
&lt;p&gt;Separate chaining is one of the most common and straightforward methods for collision resolution.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How it Works:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Instead of directly storing the key-value pair in the array slot, each slot in the hash table's array acts as a pointer to the head of a linked list (or sometimes a dynamic array). When a collision occurs, the new key-value pair is simply appended to the linked list at that specific index.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;(apple, value1) -&amp;gt; (apricot, value2)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;If keys "apple" and "apricot" both hash to index 3, the bucket at index 3 will contain a linked list as shown above.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Visual Analogy:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Think of a coat check service. Each number (hash index) corresponds to a hook. If multiple coats (key-value pairs) are assigned to the same hook, they are simply hung one after another on that same hook. When you retrieve a coat, you go to the designated hook and then search through the coats hanging there.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Pros of Separate Chaining:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Simplicity:&lt;/strong&gt; Relatively easy to implement.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficiency:&lt;/strong&gt; Handles high load factors gracefully compared to open addressing. Performance degrades linearly with the length of the linked list, but only for that specific bucket.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No Clustering:&lt;/strong&gt; Does not suffer from primary or secondary clustering, which are issues common in open addressing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deletion is Easy:&lt;/strong&gt; Removing an element is straightforward, simply deleting a node from a linked list.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Cons of Separate Chaining:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Memory Overhead:&lt;/strong&gt; Requires extra memory for pointers in the linked lists.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cache Performance:&lt;/strong&gt; Traversal of linked lists can lead to poor cache performance due to non-contiguous memory access.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Worst Case:&lt;/strong&gt; If all keys hash to the same bucket, the hash table degenerates into a single linked list, leading to O(n) performance for all operations.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="open-addressing"&gt;Open Addressing&lt;/h4&gt;
&lt;p&gt;Open addressing is another popular collision resolution technique. Instead of external data structures like linked lists, it relies on finding alternative empty slots directly within the hash table's array itself. When a collision occurs, the system "probes" for the next available slot.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How it Works:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;When a key hashes to an occupied index, the hash table calculates a new index (probe) until an empty slot is found. The way it calculates this "next" index defines the specific open addressing strategy.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Operations:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Insertion:&lt;/strong&gt; Hash the key, if the spot is taken, probe for the next empty spot. Insert there.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Lookup:&lt;/strong&gt; Hash the key, if the spot has the key, return it. If the spot is taken but not the key, probe for the next spot. Continue until the key is found or an empty spot (indicating the key is not present) is encountered.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deletion:&lt;/strong&gt; Deleting an item in open addressing is tricky. Simply removing it might break the lookup chain for other items that were probed past it. Often, a "tombstone" or "lazy deletion" marker is placed in the slot, indicating that the slot is logically empty but should not terminate a probe sequence.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Types of Probing:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Linear Probing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; When a collision occurs at index &lt;code&gt;i&lt;/code&gt;, it checks &lt;code&gt;(i+1) % array_size&lt;/code&gt;, then &lt;code&gt;(i+2) % array_size&lt;/code&gt;, and so on, until an empty slot is found.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Problem:&lt;/strong&gt; Suffers from &lt;strong&gt;primary clustering&lt;/strong&gt;, where long runs of occupied slots start to form. Any new key that hashes into such a cluster will need to traverse the entire cluster, increasing access time. This makes the table less efficient as it fills up.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Quadratic Probing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; Instead of linear steps, it probes &lt;code&gt;(i + 1^2) % array_size&lt;/code&gt;, &lt;code&gt;(i + 2^2) % array_size&lt;/code&gt;, &lt;code&gt;(i + 3^2) % array_size&lt;/code&gt;, etc.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Helps to alleviate primary clustering by skipping over immediate adjacent slots.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Problem:&lt;/strong&gt; Can suffer from &lt;strong&gt;secondary clustering&lt;/strong&gt;, where keys that initially hash to the same index follow the same probe sequence. This still leads to clusters, although they are less severe than primary clusters.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Double Hashing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; Uses a second, independent hash function &lt;code&gt;h2(key)&lt;/code&gt; to determine the step size for probing. The probe sequence becomes &lt;code&gt;(h1(key) + j * h2(key)) % array_size&lt;/code&gt;, where &lt;code&gt;j&lt;/code&gt; increments from 0.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Provides excellent dispersion and minimizes both primary and secondary clustering by generating a unique probe sequence for each key, even if they initially hash to the same spot.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Requirement:&lt;/strong&gt; The second hash function &lt;code&gt;h2(key)&lt;/code&gt; must never return zero, as that would lead to an infinite loop if the first slot is occupied.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Pros of Open Addressing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Better Cache Performance:&lt;/strong&gt; Data is stored contiguously in memory, which can lead to better cache locality and faster access times, especially for lookups.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No Pointers:&lt;/strong&gt; No overhead for linked list pointers, potentially saving memory for large tables.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Cons of Open Addressing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Sensitive to Load Factor:&lt;/strong&gt; Performance degrades sharply as the table fills up (high load factor).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deletion Complexity:&lt;/strong&gt; Deletion is more complex due to the need for "tombstones" to maintain probe sequences.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Clustering:&lt;/strong&gt; Prone to various forms of clustering, depending on the probing strategy, which can significantly slow down operations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fixed Size:&lt;/strong&gt; Typically requires rehashing into a larger table when it gets too full, which can be an expensive operation.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="key-performance-indicators-time-complexity-space"&gt;Key Performance Indicators: Time Complexity &amp;amp; Space&lt;/h2&gt;
&lt;p&gt;Understanding the performance characteristics of hash tables is crucial for their effective deployment. Their efficiency is primarily measured by time complexity for operations and their space requirements.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;The major advantage of hash tables lies in their average-case time complexity:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Average Case: O(1) (Constant Time)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;For &lt;strong&gt;insertion, deletion, and lookup&lt;/strong&gt; operations, hash tables typically achieve O(1) time complexity. This means that, on average, the time taken to perform these operations remains constant, regardless of the number of items in the table. This remarkable efficiency is due to the hash function directly calculating the bucket index, allowing for direct access in a single step (or a very small, constant number of steps in case of minor collisions).&lt;/li&gt;
&lt;li&gt;This O(1) performance holds true &lt;em&gt;provided&lt;/em&gt; that the hash function distributes keys uniformly, and the load factor is kept relatively low, minimizing the length of collision chains or probe sequences.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Worst Case: O(n) (Linear Time)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In the worst-case scenario, the performance of a hash table can degrade to O(n), where &lt;code&gt;n&lt;/code&gt; is the number of elements in the table. This happens under specific, unfortunate conditions:&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Poor Hash Function:&lt;/strong&gt; If a hash function is badly designed or intentionally malicious (e.g., in a denial-of-service attack), it might map all or most keys to the same bucket.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Extreme Collisions:&lt;/strong&gt; If all keys hash to the same index, the hash table effectively devolves into a single linked list (in separate chaining) or a linear scan of the entire array (in open addressing). In such a situation, finding, inserting, or deleting an element requires traversing up to &lt;code&gt;n&lt;/code&gt; elements.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;While rare with well-designed hash tables and hash functions, developers must be aware of this potential degradation and employ strategies to mitigate it, such as choosing robust hash functions and dynamic resizing.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;The space complexity of a hash table is generally O(n), where &lt;code&gt;n&lt;/code&gt; is the number of elements stored. This is because, at a minimum, the table needs to store each key-value pair.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Overhead:&lt;/strong&gt; There is additional space overhead:&lt;ul&gt;
&lt;li&gt;The underlying array itself, which might be larger than &lt;code&gt;n&lt;/code&gt; to accommodate empty slots and reduce collisions.&lt;/li&gt;
&lt;li&gt;Pointers for linked lists in separate chaining.&lt;/li&gt;
&lt;li&gt;Tombstone markers in open addressing (for deletions).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Trade-offs:&lt;/strong&gt; There's an inherent trade-off between space and time. A larger array (more space) generally leads to fewer collisions and better average-case time performance, while a smaller array saves space but increases the likelihood of collisions and potentially degrades time performance. Managing this trade-off effectively is a key aspect of hash table design and tuning.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="the-load-factor-a-critical-tuning-parameter"&gt;The Load Factor: A Critical Tuning Parameter&lt;/h2&gt;
&lt;p&gt;The load factor (often denoted as &lt;code&gt;α&lt;/code&gt;) is a crucial metric that quantifies how full a hash table is. It plays a significant role in determining the table's performance and is defined as:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;Load Factor (α) = Number of Entries (n) / Number of Buckets (m)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="impact-on-performance"&gt;Impact on Performance&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Low Load Factor (α &amp;lt;&amp;lt; 1):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;The table is relatively sparse, with many empty buckets.&lt;/li&gt;
&lt;li&gt;Fewer collisions, leading to faster average-case performance closer to O(1).&lt;/li&gt;
&lt;li&gt;However, it results in higher memory consumption due to many unused buckets.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;High Load Factor (α &amp;gt;= 1):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;The table is dense, with many buckets containing multiple elements (in separate chaining) or requiring longer probe sequences (in open addressing).&lt;/li&gt;
&lt;li&gt;Increased collision frequency, which degrades performance towards O(n) in the worst case.&lt;/li&gt;
&lt;li&gt;More memory efficient in terms of unused buckets, but the trade-off is often unacceptable performance.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="resizing-and-rehashing"&gt;Resizing and Rehashing&lt;/h3&gt;
&lt;p&gt;To maintain optimal performance, hash tables dynamically resize themselves when the load factor crosses a predefined threshold. This process is called &lt;strong&gt;rehashing&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;When and Why Rehashing Occurs:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Threshold:&lt;/strong&gt; Typically, when the load factor reaches a certain value (e.g., 0.7 for open addressing, or 1.0-2.0 for separate chaining), the hash table initiates a resize. This threshold is chosen to balance memory usage and collision frequency.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Procedure:&lt;/strong&gt;&lt;ol&gt;
&lt;li&gt;A new, larger array (often double the size of the original) is allocated.&lt;/li&gt;
&lt;li&gt;For each existing key-value pair in the old table:&lt;ul&gt;
&lt;li&gt;Its key is re-hashed using the hash function, but with respect to the &lt;em&gt;new, larger array size&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;The key-value pair is then inserted into the new table.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;The old, smaller array is deallocated.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Cost of Rehashing:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Rehashing is an expensive operation because it involves iterating through all existing elements and re-inserting them into a new, larger structure. This operation takes O(n) time, where &lt;code&gt;n&lt;/code&gt; is the number of elements. While individually costly, when averaged over many insertions, the amortized time complexity of insertion typically remains O(1) for a well-designed hash table that resizes geometrically (e.g., doubling its size). This amortized analysis is what allows hash tables to maintain their impressive average-case performance even with dynamic growth.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="real-world-use-cases-of-hash-tables"&gt;Real-World Use Cases of Hash Tables&lt;/h2&gt;
&lt;p&gt;Hash tables are not merely theoretical constructs; they are workhorses of modern computing, underpinning numerous everyday applications and critical infrastructure. Their ability to provide near-instantaneous access to data makes them indispensable.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Database Indexing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Scenario:&lt;/strong&gt; When you query a database for a specific record, an index can drastically speed up the search.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Application:&lt;/strong&gt; Hash tables are commonly used for database indexing (e.g., hash indexes in some NoSQL databases or specialized index types in relational databases). A key (e.g., &lt;code&gt;user_id&lt;/code&gt;) is hashed to quickly locate the disk block where the corresponding record is stored, avoiding full table scans. Understanding &lt;a href="/sql-joins-masterclass-inner-outer-left-right-explained/"&gt;SQL Joins&lt;/a&gt; is also crucial for effectively querying and combining data that these indexes support.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Enables extremely fast lookups for exact key matches.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Caching Systems:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Scenario:&lt;/strong&gt; Web servers, application servers, and even CPU caches need to store frequently accessed data for quick retrieval, avoiding expensive re-computations or disk I/O.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Application:&lt;/strong&gt; Caches are typically implemented using hash maps. The URL of a web page, a database query result, or a frequently used object becomes the key, and the cached content is the value.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Reduces latency and load by providing fast access to previously computed or fetched data.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Symbol Tables in Compilers and Interpreters:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Scenario:&lt;/strong&gt; When a compiler or interpreter processes source code, it needs to keep track of variables, functions, and their properties (e.g., type, scope).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Application:&lt;/strong&gt; Hash tables are used to implement symbol tables, mapping identifiers (variable names, function names) to their corresponding attributes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Allows for quick lookups of identifier information during lexical analysis, parsing, and semantic analysis.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Implementing Dictionaries/Maps in Programming Languages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Scenario:&lt;/strong&gt; Almost every modern programming language provides a built-in dictionary, map, or hash map data type.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Application:&lt;/strong&gt; Python's &lt;code&gt;dict&lt;/code&gt;, Java's &lt;code&gt;HashMap&lt;/code&gt;, C++'s &lt;code&gt;std::unordered_map&lt;/code&gt;, and JavaScript's &lt;code&gt;Object&lt;/code&gt; or &lt;code&gt;Map&lt;/code&gt; are all implemented using hash tables (or similar hash-based structures).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Provides programmers with a highly efficient way to store and retrieve key-value pairs without having to implement the complex logic themselves.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Set Implementations:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Scenario:&lt;/strong&gt; When you need to store a collection of unique items and quickly check for membership.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Application:&lt;/strong&gt; &lt;code&gt;HashSet&lt;/code&gt; in Java or &lt;code&gt;set&lt;/code&gt; in Python are often backed by hash tables. The presence of a key in the hash table signifies its membership in the set.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Enables O(1) average time complexity for adding elements, removing elements, and checking if an element exists in the set.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Routing Tables in Networking:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Scenario:&lt;/strong&gt; Network routers need to quickly determine the next hop for a data packet based on its destination IP address.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Application:&lt;/strong&gt; While not always pure hash tables, some high-performance routing devices use hash-based lookup mechanisms to quickly find the appropriate entry in a large routing table.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Facilitates rapid packet forwarding, critical for network throughput.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Data Deduplication:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Scenario:&lt;/strong&gt; In large storage systems or backup solutions, identifying and avoiding storage of duplicate data blocks is crucial.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Application:&lt;/strong&gt; A hash (often a cryptographic hash like SHA-256, distinct from a hash table's internal hash function) of a data block acts as a key. A hash table maps these keys to their storage locations. If a new block's hash is already in the table, it's a duplicate.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Saves significant storage space and bandwidth.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Cryptographic Applications (via Hash Functions):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Scenario:&lt;/strong&gt; Securely storing passwords, verifying data integrity, or creating digital signatures.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Application:&lt;/strong&gt; While not directly hash &lt;em&gt;tables&lt;/em&gt;, cryptographic hash functions (like MD5, SHA-256) are fundamental. They produce a fixed-size "fingerprint" of data. These fingerprints can then be stored in databases (which might use hash tables for indexing) to verify password hashes without storing the actual passwords, or to detect data tampering.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Benefit:&lt;/strong&gt; Provides security primitives for various cryptographic operations, ensuring data integrity and user authentication.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id="advantages-of-hash-tables"&gt;Advantages of Hash Tables&lt;/h2&gt;
&lt;p&gt;The widespread adoption of hash tables is a testament to their powerful advantages:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Exceptional Average-Case Performance:&lt;/strong&gt; As discussed, hash tables provide O(1) average time complexity for crucial operations like insertion, deletion, and lookup. This makes them incredibly fast for scenarios requiring quick data access, especially with large datasets.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Versatility:&lt;/strong&gt; They can store any type of key-value pair, making them adaptable to a vast array of problems and data types. From simple integers to complex custom objects, hash tables can manage diverse data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficient Memory Utilization (with proper tuning):&lt;/strong&gt; When the load factor is managed effectively, hash tables can be quite memory efficient. While there's some overhead for the underlying array and collision resolution structures, they often outperform tree-based structures in terms of space for equivalent performance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Simplicity for Programmers:&lt;/strong&gt; Most modern programming languages offer built-in hash map implementations (e.g., Python's &lt;code&gt;dict&lt;/code&gt;, Java's &lt;code&gt;HashMap&lt;/code&gt;), abstracting away the complex internal logic and allowing developers to leverage their power with minimal effort.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scalability:&lt;/strong&gt; With proper resizing strategies, hash tables can scale effectively to handle increasing amounts of data while maintaining their performance characteristics. Amortized O(1) insertions allow them to grow gracefully.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="disadvantages-and-challenges"&gt;Disadvantages and Challenges&lt;/h2&gt;
&lt;p&gt;Despite their many benefits, hash tables are not without their drawbacks and complexities:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Worst-Case Performance:&lt;/strong&gt; The Achilles' heel of hash tables is their potential O(n) worst-case performance. A poorly chosen hash function, adversarial inputs, or an extremely high load factor can lead to all elements mapping to the same bucket, degrading performance to that of a linked list or linear scan.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory Overhead:&lt;/strong&gt; While often efficient, there can be significant memory overhead. If the table is too sparse (very low load factor), a large portion of the underlying array might be empty. In separate chaining, each linked list node adds pointer overhead. In open addressing, a large array is required to keep the load factor low for optimal performance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No Inherent Ordering:&lt;/strong&gt; Hash tables do not store elements in any particular order (e.g., sorted by key). If you need to retrieve elements in sorted order, you would first have to extract all elements and then sort them, which adds an O(n log n) cost. This makes them unsuitable for applications where range queries or ordered traversal are primary requirements.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Choice of Hash Function is Crucial:&lt;/strong&gt; The performance of a hash table is highly dependent on the quality of its hash function. Designing a good, uniform hash function for complex data types can be challenging. A bad hash function can lead to excessive collisions and severely degrade performance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Load Factor Sensitivity:&lt;/strong&gt; Performance is very sensitive to the load factor. Ignoring or mismanaging the load factor can quickly turn an O(1) average-case structure into something much slower. Deciding when and how to resize is a critical design choice.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deletion Complexity (Open Addressing):&lt;/strong&gt; Deleting elements in open addressing schemes is complicated by the need for "tombstone" markers to avoid breaking probe sequences for other elements. This adds complexity and can reduce cache efficiency.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not Suitable for Small Data Sets:&lt;/strong&gt; For very small data sets, the overhead of the hash function and potential collisions might outweigh the benefits, making simpler structures like arrays or linked lists equally or more efficient.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="optimizing-hash-table-performance"&gt;Optimizing Hash Table Performance&lt;/h2&gt;
&lt;p&gt;Achieving optimal performance with hash tables requires careful consideration of several factors beyond just their basic implementation.&lt;/p&gt;
&lt;h3 id="choosing-a-good-hash-function"&gt;Choosing a Good Hash Function&lt;/h3&gt;
&lt;p&gt;This is paramount. A good hash function should:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Distribute keys uniformly:&lt;/strong&gt; Minimize collisions by spreading keys evenly across the array.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Be computationally efficient:&lt;/strong&gt; The hash calculation itself shouldn't be a bottleneck.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Be deterministic:&lt;/strong&gt; Always produce the same output for the same input.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Utilize all key bits:&lt;/strong&gt; For numerical keys, this means avoiding functions that only consider a small portion of the key. For strings, it implies considering all characters.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Avoid prime number trap:&lt;/strong&gt; For modulo operations, it is often recommended to use a prime number for the array size to help distribute keys more evenly, although modern hash functions are often more sophisticated.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="managing-load-factor-and-resizing-strategy"&gt;Managing Load Factor and Resizing Strategy&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Optimal Thresholds:&lt;/strong&gt; Select appropriate load factor thresholds for rehashing. Typically, 0.7-0.75 for open addressing and 1.0-2.0 for separate chaining are good starting points, but may need tuning based on specific data and performance requirements.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Geometric Resizing:&lt;/strong&gt; Doubling the array size (or increasing by a fixed factor like 1.5x) is a common strategy. This ensures that the amortized cost of insertion remains constant, as the expensive O(n) rehashing operations become less frequent relative to the number of insertions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pre-sizing:&lt;/strong&gt; If the approximate number of elements is known beforehand, initializing the hash table with a suitable capacity can avoid early rehashes and improve initial performance.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="selecting-the-right-collision-resolution-strategy"&gt;Selecting the Right Collision Resolution Strategy&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Separate Chaining vs. Open Addressing:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Separate Chaining:&lt;/strong&gt; Generally preferred when memory overhead for pointers is acceptable, or when load factors can become high (e.g., above 1.0). Simpler deletion. Better worst-case stability.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Open Addressing:&lt;/strong&gt; Favored when cache performance is critical due to data locality, and when memory is very tight (no pointers). Requires careful load factor management and can be more complex to implement correctly (especially deletion).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Probing Strategies (for Open Addressing):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Double Hashing:&lt;/strong&gt; Often the best choice for open addressing as it significantly reduces clustering and provides the most uniform probe sequences.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Quadratic Probing:&lt;/strong&gt; A good balance between simplicity and performance, generally better than linear probing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Linear Probing:&lt;/strong&gt; Simplest to implement but highly susceptible to primary clustering, making it suitable only for very low load factors or specific use cases.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="using-specialized-hash-table-variants"&gt;Using Specialized Hash Table Variants&lt;/h3&gt;
&lt;p&gt;For advanced scenarios, consider variants like:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Cuckoo Hashing:&lt;/strong&gt; Offers worst-case O(1) lookup and deletion by using multiple hash functions and potentially "kicking" items to new locations. Insertion can be complex.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Extendible Hashing:&lt;/strong&gt; A dynamic hashing scheme suitable for databases where hash tables need to scale to disk-based storage, dynamically growing and shrinking directories of buckets.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Consistent Hashing:&lt;/strong&gt; Primarily used in distributed systems to minimize data movement when nodes are added or removed, ensuring that only a small fraction of keys needs to be remapped.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;By carefully considering and implementing these optimization strategies, developers can harness the full power of hash tables and ensure their applications achieve peak performance for data management.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="beyond-the-basics-advanced-concepts-variations"&gt;Beyond the Basics: Advanced Concepts &amp;amp; Variations&lt;/h2&gt;
&lt;p&gt;While the fundamental concepts of hash tables revolve around hash functions and collision resolution, the field has evolved to address specific performance needs and distributed environments.&lt;/p&gt;
&lt;h3 id="cuckoo-hashing"&gt;Cuckoo Hashing&lt;/h3&gt;
&lt;p&gt;Cuckoo hashing is a highly efficient form of open addressing that guarantees worst-case O(1) lookup and deletion times. It achieves this by using multiple hash functions (typically two) and placing keys in one of the slots determined by these functions. If both slots are occupied, one of the existing keys is "kicked out" (moved to its alternative slot) to make room for the new key. This process can chain, resembling a cuckoo bird pushing eggs out of a nest. While lookup is guaranteed O(1), insertion can be complex and may occasionally fail, requiring a complete rehashing.&lt;/p&gt;
&lt;h3 id="extendible-hashing"&gt;Extendible Hashing&lt;/h3&gt;
&lt;p&gt;Designed for disk-based data structures, extendible hashing is a dynamic hashing scheme that handles growth and shrinkage efficiently. It uses a directory of pointers to buckets (pages on disk). When a bucket overflows, only that bucket splits, and the directory size can double to accommodate new pointers. This avoids rehashing the entire table when the data grows, which is crucial for large databases where data resides on slow storage.&lt;/p&gt;
&lt;h3 id="consistent-hashing"&gt;Consistent Hashing&lt;/h3&gt;
&lt;p&gt;Consistent hashing is a specialized form of hashing used primarily in distributed systems to distribute data or requests across a cluster of servers. Instead of mapping keys directly to server indices, it maps both keys and servers to positions on a conceptual ring. When a server is added or removed, only a small fraction of keys needs to be remapped, minimizing data migration and maximizing availability. This is critical for systems like content delivery networks (CDNs) and distributed caches.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="the-future-landscape-hash-tables-in-emerging-tech"&gt;The Future Landscape: Hash Tables in Emerging Tech&lt;/h2&gt;
&lt;p&gt;Hash tables, despite being a decades-old concept, continue to evolve and remain highly relevant in the landscape of emerging technologies. Their core principles of efficient data access are too valuable to be superseded.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Role in Big Data Processing:&lt;/strong&gt; As data volumes explode, efficient indexing and lookups are paramount. Hash tables are foundational to many big data processing frameworks (e.g., Apache Spark, Hadoop MapReduce) for tasks like data shuffling, aggregation, and joining large datasets. Distributed hash tables (DHTs) are key components in peer-to-peer networks and distributed storage systems, enabling vast data to be stored and retrieved across many nodes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Distributed Systems and Cloud Computing:&lt;/strong&gt; In cloud environments, applications are often distributed across numerous servers. Consistent hashing plays a crucial role in load balancing, distributed caching (e.g., Memcached, Redis clusters), and ensuring high availability and fault tolerance. Hash tables facilitate the efficient routing of requests and management of state across these distributed components.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Blockchain Technology:&lt;/strong&gt; While not hash &lt;em&gt;tables&lt;/em&gt; themselves, cryptographic hash functions are the bedrock of blockchain. Merkle trees, which rely on cryptographic hashing, are used to verify the integrity and authenticity of large data structures efficiently. The principles of creating unique, fixed-size identifiers for data pieces are shared, and the underlying storage mechanisms for blockchain data often leverage hash-based indexing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Artificial Intelligence and Machine Learning:&lt;/strong&gt; In AI/ML, hash tables are used for various purposes:&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Feature Engineering:&lt;/strong&gt; Hashing tricks are employed to transform categorical features into numerical ones efficiently, particularly in scenarios with high-dimensional sparse data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Lookup:&lt;/strong&gt; For fast retrieval of model parameters or intermediate computation results in large-scale machine learning systems.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Caching:&lt;/strong&gt; Caching frequently computed features or model predictions to speed up inference.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Nearest Neighbor Search:&lt;/strong&gt; Specialized hash-based indexing techniques (like Locality Sensitive Hashing - LSH) are used for approximate nearest neighbor searches in high-dimensional spaces, a critical component of recommendation systems and image recognition. For a more detailed understanding of the underlying principles powering many of these advancements, exploring resources like &lt;a href="/unraveling-neural-networks-beginner-guide/"&gt;Unraveling Neural Networks&lt;/a&gt; can provide valuable context.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The adaptability and fundamental efficiency of hash tables ensure their continued relevance and evolution. As data structures and algorithms continue to be optimized for new paradigms, hash tables will undoubtedly remain a cornerstone, adapting their forms to meet the challenges of tomorrow's technological landscape.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;From the earliest days of computing to the cutting edge of AI and big data, &lt;strong&gt;Hash Tables: Deep Dive into How They Work &amp;amp; Use Cases&lt;/strong&gt; reveals why these data structures have consistently proven their worth. Their ability to deliver average O(1) time complexity for essential operations like insertion, deletion, and lookup has cemented their position as an indispensable tool in the software developer's arsenal. We've explored their core components—the ingenious hash function, the fundamental array of buckets, and sophisticated collision resolution strategies—each playing a vital role in their remarkable efficiency.&lt;/p&gt;
&lt;p&gt;While challenges like potential worst-case performance and careful load factor management exist, the strategic implementation of hash tables, combined with their continuous evolution, ensures they remain a powerhouse for handling vast amounts of data swiftly. As technology advances, hash tables will undoubtedly continue to adapt and underpin the innovative applications of the future, solidifying their legacy as one of the most impactful and enduring data structures in computer science.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the primary advantage of using hash tables?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The primary advantage is their exceptional average-case time complexity of O(1) for insertion, deletion, and lookup operations. This allows for near-instantaneous access to data regardless of the dataset size, making them ideal for applications requiring rapid data retrieval.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is a hash collision, and how do hash tables handle it?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A hash collision occurs when two different keys generate the same index using the hash function. Hash tables resolve this using strategies like separate chaining, where multiple key-value pairs at the same index are stored in a linked list, or open addressing, which finds an alternative empty slot within the array.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: When is a hash table not the ideal data structure to use?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Hash tables are not ideal when data needs to be stored or retrieved in a sorted order, as they do not maintain any inherent order. Their performance can also degrade significantly to O(n) in worst-case scenarios with a poor hash function or high load factor, making them unsuitable where strict worst-case guarantees are required.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/hashing-data-structure/"&gt;Introduction to Hash Tables (GeeksforGeeks)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=shs0KM3wPDU"&gt;Hash Tables Explained (YouTube by freeCodeCamp.org)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011/resources/lecture-6-hashing-i/"&gt;Data Structures &amp;amp; Algorithms: Hash Tables (MIT OpenCourseWare)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries"&gt;Python Dictionaries (Official Python Docs)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Data Structures"/><category term="Algorithms"/><category term="Technology"/><category term="Python"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/hash-tables-deep-dive-how-they-work-use-cases.webp" width="1200"/><media:title type="plain">Hash Tables: Deep Dive into Their Inner Workings &amp; Use Cases</media:title><media:description type="plain">Unlock the power of Hash Tables: Deep Dive into How They Work &amp; Use Cases. Explore their O(1) efficiency, essential components, and widespread applications i...</media:description></entry><entry><title>QuickSort Algorithm Explained: A Step-by-Step Guide for Developers</title><link href="https://analyticsdrive.tech/quicksort-algorithm-explained-step-by-step-guide/" rel="alternate"/><published>2026-03-18T14:23:00+05:30</published><updated>2026-03-18T14:23:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-18:/quicksort-algorithm-explained-step-by-step-guide/</id><summary type="html">&lt;p&gt;Demystify the QuickSort Algorithm Explained: A Step-by-Step Guide for developers. Learn its mechanics, complexity, and practical applications in depth.&lt;/p&gt;</summary><content type="html">&lt;p&gt;The world of computer science is replete with elegant solutions to fundamental problems, and sorting data efficiently stands as one of its cornerstones. Among the pantheon of sorting algorithms, QuickSort holds a distinguished position, renowned for its average-case speed and in-place nature. For anyone looking to truly master data manipulation, understanding this algorithm is non-negotiable. This comprehensive article provides a "QuickSort Algorithm Explained: A Step-by-Step Guide" designed to demystify its inner workings, equip you with practical knowledge, and illuminate its real-world relevance. We will delve deep into its mechanics, explore various implementation strategies, analyze its performance, and compare it with other prominent sorting methods, giving developers a definitive resource.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-quicksort-a-foundation-of-efficient-sorting"&gt;What is QuickSort? A Foundation of Efficient Sorting&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-divide-and-conquer-paradigm"&gt;The Divide and Conquer Paradigm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-quicksort-algorithm-explained-a-step-by-step-guide-to-its-fundamental-principles"&gt;The QuickSort Algorithm Explained: A Step-by-Step Guide to Its Fundamental Principles&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-choosing-a-pivot-element"&gt;1. Choosing a Pivot Element&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-partitioning-the-array"&gt;2. Partitioning the Array&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#lomuto-partition-scheme"&gt;Lomuto Partition Scheme&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#hoare-partition-scheme"&gt;Hoare Partition Scheme&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-recursive-application"&gt;3. Recursive Application&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-quicksort-in-python"&gt;Implementing QuickSort in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#key-characteristics-performance-analysis-of-quicksort"&gt;Key Characteristics &amp;amp; Performance Analysis of QuickSort&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#stability"&gt;Stability&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#in-place-sorting"&gt;In-Place Sorting&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#quicksort-vs-other-sorting-algorithms"&gt;QuickSort vs. Other Sorting Algorithms&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#quicksort-vs-mergesort"&gt;QuickSort vs. MergeSort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#quicksort-vs-heapsort"&gt;QuickSort vs. HeapSort&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-quicksort"&gt;Real-World Applications of QuickSort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#advantages-and-disadvantages-of-quicksort"&gt;Advantages and Disadvantages of QuickSort&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#advantages"&gt;Advantages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#disadvantages"&gt;Disadvantages&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#optimizations-and-variations"&gt;Optimizations and Variations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-robust-pivot-selection"&gt;1. Robust Pivot Selection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-handling-small-sub-arrays"&gt;2. Handling Small Sub-arrays&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-introsort-introspective-sort"&gt;3. Introsort (Introspective Sort)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-three-way-partitioning-dutch-national-flag-problem"&gt;4. Three-Way Partitioning (Dutch National Flag Problem)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-pitfalls-and-how-to-avoid-them"&gt;Common Pitfalls and How to Avoid Them&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-poor-pivot-selection"&gt;1. Poor Pivot Selection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-stack-overflow"&gt;2. Stack Overflow&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-off-by-one-errors-in-partitioning"&gt;3. Off-by-One Errors in Partitioning&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-inefficient-handling-of-duplicates"&gt;4. Inefficient Handling of Duplicates&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion-mastering-the-quicksort-algorithm"&gt;Conclusion: Mastering the QuickSort Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id="what-is-quicksort-a-foundation-of-efficient-sorting"&gt;What is QuickSort? A Foundation of Efficient Sorting&lt;/h2&gt;
&lt;p&gt;QuickSort is an efficient, comparison-based sorting algorithm, developed by Sir Tony Hoare in 1959 and published in 1961. Often regarded as one of the fastest general-purpose sorting algorithms, especially for large datasets, it operates on the principle of divide and conquer. This means it breaks down a problem into smaller, more manageable sub-problems, solves them independently, and then combines their solutions.&lt;/p&gt;
&lt;p&gt;Unlike some other sorting algorithms that rely on external &lt;a href="/demystifying-binary-trees-structure-traversal-use/"&gt;data structures&lt;/a&gt; or significant additional memory, QuickSort typically sorts data "in-place," meaning it requires minimal additional storage space. This characteristic makes it highly valuable in scenarios where memory is a constraint. Its power lies in its simplicity and efficiency, especially in its average-case performance.&lt;/p&gt;
&lt;h3 id="the-divide-and-conquer-paradigm"&gt;The Divide and Conquer Paradigm&lt;/h3&gt;
&lt;p&gt;To fully appreciate QuickSort, it's essential to grasp the essence of the divide and conquer paradigm:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Divide:&lt;/strong&gt; The problem is broken down into several sub-problems that are similar to the original problem but smaller in size.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Conquer:&lt;/strong&gt; The sub-problems are solved recursively. If the sub-problem is small enough, it is solved directly (base case).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Combine:&lt;/strong&gt; The solutions to the sub-problems are combined to get the solution to the original problem.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In QuickSort's context, the "divide" step involves partitioning the array. The "conquer" step is the recursive sorting of sub-arrays, and the "combine" step is implicit as the partitioning itself places elements in their correct relative positions.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="the-quicksort-algorithm-explained-a-step-by-step-guide-to-its-fundamental-principles"&gt;The QuickSort Algorithm Explained: A Step-by-Step Guide to Its Fundamental Principles&lt;/h2&gt;
&lt;p&gt;At its heart, QuickSort's operational model revolves around three critical steps: choosing a pivot element, partitioning the array around that pivot, and recursively applying the process to the sub-arrays. This iterative refinement is what drives its efficiency. Let's break down these principles.&lt;/p&gt;
&lt;h3 id="1-choosing-a-pivot-element"&gt;1. Choosing a Pivot Element&lt;/h3&gt;
&lt;p&gt;The pivot is a crucial element in QuickSort. It acts as a reference point around which the array will be divided. The goal is to place the pivot in its correct sorted position within the array. Elements smaller than the pivot will go to its left, and elements larger than the pivot will go to its right.&lt;/p&gt;
&lt;p&gt;There are several strategies for selecting a pivot:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;First Element:&lt;/strong&gt; Choosing the element at the beginning of the sub-array. Simple, but can lead to worst-case performance on already sorted or reverse-sorted arrays.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Last Element:&lt;/strong&gt; Choosing the element at the end of the sub-array. Also simple and susceptible to similar worst-case scenarios.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Middle Element:&lt;/strong&gt; Selecting the element in the middle index. A slight improvement over first/last but still prone to issues with specific data distributions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Random Element:&lt;/strong&gt; Picking a pivot randomly from the sub-array. This strategy helps mitigate the risk of worst-case performance for specific input types, as the chance of consistently picking a "bad" pivot decreases.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Median-of-Three:&lt;/strong&gt; Selecting the median of the first, middle, and last elements. This is a robust strategy that often leads to better average performance by choosing a pivot closer to the actual median of the sub-array.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The choice of pivot strategy significantly impacts the algorithm's performance, particularly in terms of its best, average, and worst-case time complexities. A poorly chosen pivot can lead to highly unbalanced partitions, degrading performance.&lt;/p&gt;
&lt;h3 id="2-partitioning-the-array"&gt;2. Partitioning the Array&lt;/h3&gt;
&lt;p&gt;Once a pivot is selected, the partitioning step rearranges the elements in the sub-array such that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;All elements less than or equal to the pivot are moved to its left.&lt;/li&gt;
&lt;li&gt;All elements greater than the pivot are moved to its right.&lt;/li&gt;
&lt;li&gt;The pivot element itself is placed in its final sorted position.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This process ensures that after one partitioning step, the pivot is correctly positioned, and the sub-problems (the arrays to its left and right) are ready for recursive sorting.&lt;/p&gt;
&lt;p&gt;There are two primary partitioning schemes:&lt;/p&gt;
&lt;h4 id="lomuto-partition-scheme"&gt;Lomuto Partition Scheme&lt;/h4&gt;
&lt;p&gt;The Lomuto partition scheme is generally simpler to understand and implement. It typically uses the last element as the pivot (though any element can be moved to the last position and then used).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How it works:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Select the last element as the pivot.&lt;/li&gt;
&lt;li&gt;Initialize an index &lt;code&gt;i&lt;/code&gt; (smaller element index) to &lt;code&gt;low - 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Iterate &lt;code&gt;j&lt;/code&gt; from &lt;code&gt;low&lt;/code&gt; to &lt;code&gt;high - 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;arr[j]&lt;/code&gt; is less than or equal to the pivot, increment &lt;code&gt;i&lt;/code&gt; and swap &lt;code&gt;arr[i]&lt;/code&gt; with &lt;code&gt;arr[j]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;After the loop, swap &lt;code&gt;arr[i + 1]&lt;/code&gt; with &lt;code&gt;arr[high]&lt;/code&gt; (the pivot).&lt;/li&gt;
&lt;li&gt;Return &lt;code&gt;i + 1&lt;/code&gt;, which is the pivot's final position.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Example walkthrough (Lomuto, last element as pivot):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let's sort &lt;code&gt;[10, 7, 8, 9, 1, 5]&lt;/code&gt; using the Lomuto partition.
&lt;code&gt;low = 0&lt;/code&gt;, &lt;code&gt;high = 5&lt;/code&gt;.
&lt;strong&gt;Pivot = &lt;code&gt;arr[high]&lt;/code&gt; = &lt;code&gt;arr[5]&lt;/code&gt; = 5.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;i = -1&lt;/code&gt; (conceptually &lt;code&gt;low - 1&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Initial Array:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;[10, 7, 8, 9, 1, 5]
 ^                 ^
low               high, pivot=5
i=-1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Iteration &lt;code&gt;j&lt;/code&gt; from 0 to &lt;code&gt;high-1&lt;/code&gt; (4):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;j = 0&lt;/code&gt;, &lt;code&gt;arr[0] = 10&lt;/code&gt;. Is &lt;code&gt;10 &amp;lt;= 5&lt;/code&gt;? No.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;j = 1&lt;/code&gt;, &lt;code&gt;arr[1] = 7&lt;/code&gt;. Is &lt;code&gt;7 &amp;lt;= 5&lt;/code&gt;? No.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;j = 2&lt;/code&gt;, &lt;code&gt;arr[2] = 8&lt;/code&gt;. Is &lt;code&gt;8 &amp;lt;= 5&lt;/code&gt;? No.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;j = 3&lt;/code&gt;, &lt;code&gt;arr[3] = 9&lt;/code&gt;. Is &lt;code&gt;9 &amp;lt;= 5&lt;/code&gt;? No.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;j = 4&lt;/code&gt;, &lt;code&gt;arr[4] = 1&lt;/code&gt;. Is &lt;code&gt;1 &amp;lt;= 5&lt;/code&gt;? Yes.&lt;ul&gt;
&lt;li&gt;Increment &lt;code&gt;i&lt;/code&gt; to 0.&lt;/li&gt;
&lt;li&gt;Swap &lt;code&gt;arr[0]&lt;/code&gt; (10) and &lt;code&gt;arr[4]&lt;/code&gt; (1).&lt;/li&gt;
&lt;li&gt;Array becomes: &lt;code&gt;[1, 7, 8, 9, 10, 5]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;i=0&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;[1, 7, 8, 9, 10, 5]
 ^
 i
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Loop ends.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Swap &lt;code&gt;arr[i + 1]&lt;/code&gt; (&lt;code&gt;arr[1]&lt;/code&gt;, which is 7) with &lt;code&gt;arr[high]&lt;/code&gt; (&lt;code&gt;arr[5]&lt;/code&gt;, which is 5).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Array becomes:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;[1, 5, 8, 9, 10, 7]
   ^
   Pivot (5) is now at index 1.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The function returns &lt;code&gt;i + 1&lt;/code&gt;, which is 1. Now, all elements to the left of index 1 are &lt;code&gt;&amp;lt;= 5&lt;/code&gt;, and elements to the right are &lt;code&gt;&amp;gt;= 5&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id="hoare-partition-scheme"&gt;Hoare Partition Scheme&lt;/h4&gt;
&lt;p&gt;The Hoare partition scheme, the original one developed by Hoare, is generally more efficient than Lomuto, as it performs fewer swaps on average. It works with two pointers, &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;j&lt;/code&gt;, that start from opposite ends of the array and move towards each other.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How it works:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Select a pivot (often the first element, or median-of-three for robustness).&lt;/li&gt;
&lt;li&gt;Initialize &lt;code&gt;i = low - 1&lt;/code&gt; and &lt;code&gt;j = high + 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Enter an infinite loop:&lt;ul&gt;
&lt;li&gt;Increment &lt;code&gt;i&lt;/code&gt; until &lt;code&gt;arr[i]&lt;/code&gt; is greater than or equal to the pivot.&lt;/li&gt;
&lt;li&gt;Decrement &lt;code&gt;j&lt;/code&gt; until &lt;code&gt;arr[j]&lt;/code&gt; is less than or equal to the pivot.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;i &amp;gt;= j&lt;/code&gt;, break the loop (partition complete, &lt;code&gt;j&lt;/code&gt; is the pivot index).&lt;/li&gt;
&lt;li&gt;Otherwise, swap &lt;code&gt;arr[i]&lt;/code&gt; and &lt;code&gt;arr[j]&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Return &lt;code&gt;j&lt;/code&gt; (the final position of the pivot or where the sub-arrays should be divided).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The key difference is that Lomuto places elements equal to the pivot on the left, while Hoare allows them on either side, which can reduce swaps for arrays with many duplicates.&lt;/p&gt;
&lt;h3 id="3-recursive-application"&gt;3. Recursive Application&lt;/h3&gt;
&lt;p&gt;After the partitioning step, the pivot is in its correct sorted position. The original array is now conceptually divided into two sub-arrays:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The sub-array of elements to the left of the pivot (all less than or equal to the pivot).&lt;/li&gt;
&lt;li&gt;The sub-array of elements to the right of the pivot (all greater than or equal to the pivot).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;QuickSort then recursively calls itself on these two sub-arrays. This process continues until a sub-array contains zero or one element, which is the base case for the recursion (a single-element array is already sorted). Because the pivot is already in its final place, it's excluded from further recursive calls.&lt;/p&gt;
&lt;p&gt;This recursive nature is what allows QuickSort to progressively refine the order of elements across the entire dataset.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="implementing-quicksort-in-python"&gt;Implementing QuickSort in Python&lt;/h2&gt;
&lt;p&gt;Let's put these principles into action with a Python implementation. We'll use the Lomuto partition scheme for its clarity and common use in educational contexts, with the last element as the pivot.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;swap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Helper function to swap two elements in an array.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;partition&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;    This function takes the last element as pivot, places the pivot element&lt;/span&gt;
&lt;span class="sd"&gt;    at its correct position in sorted array, and places all smaller (than pivot)&lt;/span&gt;
&lt;span class="sd"&gt;    to left of pivot and all greater elements to right of pivot.&lt;/span&gt;
&lt;span class="sd"&gt;    &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="n"&gt;pivot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="c1"&gt;# Choose the last element as the pivot&lt;/span&gt;
    &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;low&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;        &lt;span class="c1"&gt;# Index of smaller element&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# If current element is smaller than or equal to pivot&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;pivot&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="n"&gt;swap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Place the pivot element in its correct position&lt;/span&gt;
    &lt;span class="n"&gt;swap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;quick_sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;    The main function that implements QuickSort.&lt;/span&gt;
&lt;span class="sd"&gt;    arr --&amp;gt; Array to be sorted,&lt;/span&gt;
&lt;span class="sd"&gt;    low  --&amp;gt; Starting index,&lt;/span&gt;
&lt;span class="sd"&gt;    high  --&amp;gt; Ending index.&lt;/span&gt;
&lt;span class="sd"&gt;    &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;low&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# pi is partitioning index, arr[pi] is now at right place&lt;/span&gt;
        &lt;span class="n"&gt;pi&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;partition&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Separately sort elements before partition and after partition&lt;/span&gt;
        &lt;span class="n"&gt;quick_sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;low&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pi&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;quick_sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pi&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;high&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Example Usage:&lt;/span&gt;
&lt;span class="c1"&gt;# my_list = [10, 7, 8, 9, 1, 5, 12, 3, 22, 11, 4]&lt;/span&gt;
&lt;span class="c1"&gt;# n = len(my_list)&lt;/span&gt;
&lt;span class="c1"&gt;# quick_sort(my_list, 0, n - 1)&lt;/span&gt;
&lt;span class="c1"&gt;# print(&amp;quot;Sorted array is:&amp;quot;, my_list)&lt;/span&gt;
&lt;span class="c1"&gt;# Expected Output: Sorted array is: [1, 3, 4, 5, 7, 8, 9, 10, 11, 12, 22]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Code Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;swap(arr, i, j)&lt;/code&gt;:&lt;/strong&gt; A simple utility function to exchange two elements. This is fundamental to rearranging elements during partitioning.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;partition(arr, low, high)&lt;/code&gt;:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;It selects the &lt;code&gt;arr[high]&lt;/code&gt; as the pivot.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;i&lt;/code&gt; tracks the boundary of elements that are less than or equal to the pivot.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;for&lt;/code&gt; loop iterates from &lt;code&gt;low&lt;/code&gt; to &lt;code&gt;high - 1&lt;/code&gt;. If &lt;code&gt;arr[j]&lt;/code&gt; is found to be less than or equal to the pivot, &lt;code&gt;i&lt;/code&gt; is incremented, and &lt;code&gt;arr[i]&lt;/code&gt; and &lt;code&gt;arr[j]&lt;/code&gt; are swapped. This effectively moves smaller elements to the left side of &lt;code&gt;i&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Finally, the pivot (&lt;code&gt;arr[high]&lt;/code&gt;) is swapped with &lt;code&gt;arr[i + 1]&lt;/code&gt;, placing it in its correct sorted position.&lt;/li&gt;
&lt;li&gt;The index &lt;code&gt;i + 1&lt;/code&gt; (the pivot's final position) is returned, which will be used to divide the array for recursive calls.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;quick_sort(arr, low, high)&lt;/code&gt;:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;This is the recursive function. The base case for recursion is &lt;code&gt;low &amp;lt; high&lt;/code&gt;. If &lt;code&gt;low &amp;gt;= high&lt;/code&gt;, it means the sub-array has 0 or 1 element and is already sorted.&lt;/li&gt;
&lt;li&gt;It calls &lt;code&gt;partition&lt;/code&gt; to get the pivot's sorted index (&lt;code&gt;pi&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Then, it recursively calls &lt;code&gt;quick_sort&lt;/code&gt; for the left sub-array (&lt;code&gt;low&lt;/code&gt; to &lt;code&gt;pi - 1&lt;/code&gt;) and the right sub-array (&lt;code&gt;pi + 1&lt;/code&gt; to &lt;code&gt;high&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This structured approach, using helper functions, makes the QuickSort logic clear and easy to follow.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="key-characteristics-performance-analysis-of-quicksort"&gt;Key Characteristics &amp;amp; Performance Analysis of QuickSort&lt;/h2&gt;
&lt;p&gt;Understanding the performance profile of QuickSort is crucial for any developer deciding when and where to employ it. Its characteristics define its suitability for various computational tasks.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;Time complexity measures how the running time of an algorithm grows with the size of the input data (&lt;code&gt;n&lt;/code&gt;).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Best Case: O(n log n)&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;This occurs when the pivot consistently divides the array into two roughly equal halves. Each partitioning step takes &lt;code&gt;O(n)&lt;/code&gt; time (as it processes &lt;code&gt;n&lt;/code&gt; elements). If the array is perfectly halved at each step, there will be &lt;code&gt;log n&lt;/code&gt; levels of recursion. Thus, &lt;code&gt;n * log n&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Example: Choosing the true median as the pivot every time.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Average Case: O(n log n)&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Statistically, even with random pivot choices, QuickSort performs exceptionally well on average. The expectation of getting partitions that are not extremely skewed leads to &lt;code&gt;O(n log n)&lt;/code&gt; performance. Empirical studies and theoretical analyses confirm this.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Worst Case: O(n^2)&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;This happens when the pivot consistently produces highly unbalanced partitions, typically when the smallest or largest element is always chosen as the pivot.&lt;/li&gt;
&lt;li&gt;For example, if the array is already sorted or reverse-sorted, and you consistently pick the first or last element as the pivot, one sub-array will always be empty, and the other will contain &lt;code&gt;n-1&lt;/code&gt; elements. This degenerates into &lt;code&gt;n&lt;/code&gt; levels of recursion, with each level taking &lt;code&gt;O(n)&lt;/code&gt; work, leading to &lt;code&gt;O(n^2)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Example: Sorting &lt;code&gt;[1, 2, 3, 4, 5]&lt;/code&gt; by always picking the last element as the pivot.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The practical implication is that while &lt;code&gt;O(n^2)&lt;/code&gt; is theoretically possible, well-implemented QuickSort versions (e.g., using random pivot or median-of-three) make it a rare occurrence in real-world scenarios.&lt;/p&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;Space complexity measures the amount of temporary storage an algorithm uses.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Worst Case: O(n)&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;In the worst-case scenario (e.g., an already sorted array with the first element always picked as pivot), the recursive calls might stack up to a depth of &lt;code&gt;n&lt;/code&gt;. Each call adds a frame to the call stack, consuming &lt;code&gt;O(n)&lt;/code&gt; space.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Average Case: O(log n)&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;On average, when the partitions are relatively balanced, the depth of the recursion tree is &lt;code&gt;log n&lt;/code&gt;. Thus, the space required for the call stack is &lt;code&gt;O(log n)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Some implementations optimize space by tail-recursion optimization or by always recursing on the smaller sub-array first, which can limit the stack depth to &lt;code&gt;O(log n)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;QuickSort is considered an "in-place" sorting algorithm because it primarily sorts within the original array, requiring only a small amount of auxiliary space for the recursion stack.&lt;/p&gt;
&lt;h3 id="stability"&gt;Stability&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Not Stable:&lt;/strong&gt; QuickSort is generally not a stable sorting algorithm. Stability refers to whether the relative order of equal elements is preserved after sorting.&lt;ul&gt;
&lt;li&gt;During the partitioning process, elements with the same value as the pivot, or other elements, might be swapped in a way that changes their original relative order. For instance, if you have &lt;code&gt;[5a, 3, 5b]&lt;/code&gt; and 5 is the pivot, &lt;code&gt;5b&lt;/code&gt; might end up before &lt;code&gt;5a&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;While stable versions of QuickSort exist, they usually come at the cost of increased time or space complexity.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="in-place-sorting"&gt;In-Place Sorting&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Yes:&lt;/strong&gt; QuickSort is an in-place sorting algorithm. This means it transforms the input by working directly on the data structure itself, without requiring extra space proportional to the input size. The only extra space needed is for the recursion stack, which is &lt;code&gt;O(log n)&lt;/code&gt; on average. This is a significant advantage for memory-constrained environments or very large datasets.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="quicksort-vs-other-sorting-algorithms"&gt;QuickSort vs. Other Sorting Algorithms&lt;/h2&gt;
&lt;p&gt;To truly appreciate QuickSort, it's beneficial to compare it with other prominent sorting algorithms that also achieve &lt;code&gt;O(n log n)&lt;/code&gt; average-case time complexity.&lt;/p&gt;
&lt;h3 id="quicksort-vs-mergesort"&gt;QuickSort vs. MergeSort&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style="text-align: left;"&gt;Feature&lt;/th&gt;
&lt;th style="text-align: left;"&gt;QuickSort&lt;/th&gt;
&lt;th style="text-align: left;"&gt;MergeSort&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Time Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n log n) average, O(n^2) worst&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n log n) best, average, worst&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Space Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(log n) average, O(n) worst (for recursion)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n) (for auxiliary array)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Stability&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Not stable&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Stable&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;In-Place&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Yes (requires stack space)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;No (requires auxiliary array for merging)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Performance&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Generally faster in practice due to better cache performance and fewer memory writes.&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Predictable performance, good for external sorting.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Paradigm&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Divide and Conquer (partitioning is key)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Divide and Conquer (merging is key)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;Key Differences:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Memory:&lt;/strong&gt; QuickSort is in-place, while MergeSort typically requires &lt;code&gt;O(n)&lt;/code&gt; auxiliary space for merging. This makes QuickSort preferable when memory is limited.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Worst-case:&lt;/strong&gt; MergeSort guarantees &lt;code&gt;O(n log n)&lt;/code&gt; performance, making it a safer choice when worst-case performance is critical. QuickSort's &lt;code&gt;O(n^2)&lt;/code&gt; worst-case is a concern, though often mitigated.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Stability:&lt;/strong&gt; MergeSort is stable, preserving the relative order of equal elements, which can be important for certain applications. QuickSort is not.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cache Performance:&lt;/strong&gt; QuickSort often has better cache performance than MergeSort because it works on contiguous memory blocks more often, leading to fewer cache misses.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="quicksort-vs-heapsort"&gt;QuickSort vs. HeapSort&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style="text-align: left;"&gt;Feature&lt;/th&gt;
&lt;th style="text-align: left;"&gt;QuickSort&lt;/th&gt;
&lt;th style="text-align: left;"&gt;HeapSort&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Time Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n log n) average, O(n^2) worst&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(n log n) best, average, worst&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Space Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(log n) average, O(n) worst (for recursion)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;O(1) (in-place)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Stability&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Not stable&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Not stable&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;In-Place&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Yes (requires stack space)&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Yes (strictly in-place)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Performance&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Generally faster in practice due for practical reasons like cache-coherence.&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Slower than QuickSort in practice but guarantees O(n log n) in all cases.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Paradigm&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Divide and Conquer&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Selection-based (uses a binary heap)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;Key Differences:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Guaranteed Performance:&lt;/strong&gt; HeapSort offers a guaranteed &lt;code&gt;O(n log n)&lt;/code&gt; worst-case time complexity, making it robust against pathological inputs that can degrade QuickSort to &lt;code&gt;O(n^2)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;True In-Place:&lt;/strong&gt; HeapSort is truly &lt;code&gt;O(1)&lt;/code&gt; auxiliary space, as it doesn't even need a recursion stack. This makes it ideal for extremely memory-constrained environments.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Practical Speed:&lt;/strong&gt; Despite the theoretical advantage of HeapSort's guaranteed &lt;code&gt;O(n log n)&lt;/code&gt;, QuickSort is often faster in practice due to its superior cache locality and smaller constant factors. The random memory access patterns of heap operations can lead to more cache misses.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In summary, QuickSort remains a popular choice for its average-case speed and in-place nature. MergeSort is preferred for guaranteed performance and stability, while HeapSort is excellent for strict memory constraints and guaranteed worst-case time.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="real-world-applications-of-quicksort"&gt;Real-World Applications of QuickSort&lt;/h2&gt;
&lt;p&gt;Given its efficiency and in-place sorting capability, QuickSort is widely used across various domains in computer science and software engineering.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Standard Library Implementations:&lt;/strong&gt; Many programming languages' built-in sorting functions (e.g., C++ &lt;code&gt;std::sort&lt;/code&gt;, Java's &lt;code&gt;Arrays.sort()&lt;/code&gt; for primitive types) are often based on QuickSort or hybrid algorithms that incorporate QuickSort (like Introsort, which switches to HeapSort in the worst case).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Database Systems:&lt;/strong&gt; QuickSort can be used internally by database management systems for sorting query results or indexing large tables. Its efficiency with large datasets makes it suitable for operations like &lt;code&gt;ORDER BY&lt;/code&gt; clauses.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Analytics and Processing:&lt;/strong&gt; In fields involving large-scale data processing, QuickSort is employed to sort data for further analysis, such as finding medians, percentiles, or preparing data for machine learning models. For instance, in data warehousing, sorting might be a preliminary step for various aggregate functions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Operating Systems:&lt;/strong&gt; Operating systems may use QuickSort for tasks like sorting process lists, file directories, or memory management segments.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Computational Geometry:&lt;/strong&gt; Many algorithms in computational geometry (e.g., convex hull, closest pair of points) require sorting points or coordinates as an initial step, where QuickSort is a common choice. For more advanced algorithmic challenges often seen in competitive programming, consider exploring resources like our guide on &lt;a href="/839-similar-string-groups-leetcode-python-cpp-java-tutorial/"&gt;LeetCode problem solutions&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graphics and Image Processing:&lt;/strong&gt; QuickSort can be used in rendering algorithms, especially for sorting objects by depth or other properties before drawing them to ensure correct overlaying.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The prevalence of QuickSort in these applications underscores its practical utility and robust performance characteristics.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="advantages-and-disadvantages-of-quicksort"&gt;Advantages and Disadvantages of QuickSort&lt;/h2&gt;
&lt;p&gt;Like any algorithm, QuickSort comes with its own set of pros and cons that dictate its applicability.&lt;/p&gt;
&lt;h3 id="advantages"&gt;Advantages&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Fast in Practice:&lt;/strong&gt; QuickSort is one of the fastest sorting algorithms in practice, especially for large inputs, largely due to its efficient partitioning and good cache performance. It often outperforms other &lt;code&gt;O(n log n)&lt;/code&gt; algorithms like HeapSort and MergeSort in real-world benchmarks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;In-Place Sorting:&lt;/strong&gt; It sorts the array without requiring significant additional memory, making it ideal for memory-constrained environments. Its average space complexity is &lt;code&gt;O(log n)&lt;/code&gt; for the recursion stack.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cache-Friendly:&lt;/strong&gt; QuickSort accesses data in a relatively sequential manner, especially during the partitioning phase. This spatial locality of reference leads to fewer cache misses, making it faster on modern computer architectures.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Adaptive to Hardware:&lt;/strong&gt; Its performance scales well with better hardware due to the above-mentioned cache efficiency.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="disadvantages"&gt;Disadvantages&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Worst-Case Performance:&lt;/strong&gt; The primary disadvantage is its &lt;code&gt;O(n^2)&lt;/code&gt; worst-case time complexity, which can occur with consistently poor pivot choices (e.g., sorted arrays when the first/last element is always chosen as pivot). This makes it unsuitable for applications where guaranteed upper bounds on performance are critical.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not Stable:&lt;/strong&gt; QuickSort is generally not a stable sorting algorithm, meaning the relative order of equal elements is not preserved. This can be a drawback in applications where stability is a requirement (e.g., sorting database records by multiple keys).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursive Overhead:&lt;/strong&gt; The recursive nature of QuickSort incurs a certain amount of overhead due to function call stack management. For very small arrays, iterative sorting algorithms or simpler sorts (like Insertion Sort) might be faster due to less overhead.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Implementation Complexity:&lt;/strong&gt; While the basic idea is simple, optimizing QuickSort for all edge cases (like handling duplicates efficiently or choosing a robust pivot) and ensuring against stack overflow can make advanced implementations more complex.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Developers must weigh these advantages and disadvantages carefully when selecting QuickSort for a specific task, often opting for hybrid approaches in robust library implementations.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="optimizations-and-variations"&gt;Optimizations and Variations&lt;/h2&gt;
&lt;p&gt;To mitigate QuickSort's disadvantages and enhance its performance across various scenarios, several optimizations and variations have been developed.&lt;/p&gt;
&lt;h3 id="1-robust-pivot-selection"&gt;1. Robust Pivot Selection&lt;/h3&gt;
&lt;p&gt;As discussed, the pivot choice is critical.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Random Pivot:&lt;/strong&gt; Choosing a pivot randomly helps to avoid the worst-case scenario for most inputs, as the chance of consistently picking a bad pivot decreases.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Median-of-Three:&lt;/strong&gt; Selecting the median of the first, middle, and last elements as the pivot is a common optimization. This provides a better estimate of the true median, leading to more balanced partitions on average and making the &lt;code&gt;O(n^2)&lt;/code&gt; worst-case less likely.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-handling-small-sub-arrays"&gt;2. Handling Small Sub-arrays&lt;/h3&gt;
&lt;p&gt;For very small sub-arrays (e.g., &lt;code&gt;n &amp;lt; 10-20&lt;/code&gt; elements), QuickSort's recursive overhead can make it less efficient than simpler sorting algorithms.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Hybrid Approach:&lt;/strong&gt; A common optimization is to stop QuickSort recursion when sub-arrays become very small and then use an algorithm like Insertion Sort for those small sub-arrays. Insertion Sort is highly efficient for nearly sorted or very small arrays. This combined approach leverages the strengths of both algorithms.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-introsort-introspective-sort"&gt;3. Introsort (Introspective Sort)&lt;/h3&gt;
&lt;p&gt;Introsort is a hybrid sorting algorithm that combines the best features of QuickSort, HeapSort, and Insertion Sort. It's often the default sorting algorithm in standard libraries.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;It starts with QuickSort due to its excellent average-case performance.&lt;/li&gt;
&lt;li&gt;If the recursion depth exceeds a certain limit (indicating a potentially pathological input leading to QuickSort's &lt;code&gt;O(n^2)&lt;/code&gt; worst case), it switches to HeapSort, which guarantees &lt;code&gt;O(n log n)&lt;/code&gt; performance.&lt;/li&gt;
&lt;li&gt;For very small partitions, it switches to Insertion Sort, which is efficient for small arrays and has low overhead.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This strategy ensures robust &lt;code&gt;O(n log n)&lt;/code&gt; worst-case performance while retaining QuickSort's typical speed.&lt;/p&gt;
&lt;h3 id="4-three-way-partitioning-dutch-national-flag-problem"&gt;4. Three-Way Partitioning (Dutch National Flag Problem)&lt;/h3&gt;
&lt;p&gt;When an array contains many duplicate elements, standard QuickSort can be inefficient because elements equal to the pivot are often repeatedly swapped or end up in sub-arrays where they don't help much.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Three-Way Partitioning:&lt;/strong&gt; This variation partitions the array into three segments:&lt;ol&gt;
&lt;li&gt;Elements less than the pivot.&lt;/li&gt;
&lt;li&gt;Elements equal to the pivot.&lt;/li&gt;
&lt;li&gt;Elements greater than the pivot.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;The middle segment (elements equal to the pivot) is already sorted and does not need further recursive calls. This significantly improves performance when dealing with arrays containing a large number of duplicate values. Algorithms like &lt;code&gt;qsort&lt;/code&gt; in C and &lt;code&gt;Arrays.sort&lt;/code&gt; in Java use this optimization.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These optimizations collectively make QuickSort a highly adaptable and robust algorithm, explaining its pervasive use in high-performance computing.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="common-pitfalls-and-how-to-avoid-them"&gt;Common Pitfalls and How to Avoid Them&lt;/h2&gt;
&lt;p&gt;Even with its advantages, QuickSort implementation can stumble upon common issues. Awareness of these can save significant debugging time and performance headaches.&lt;/p&gt;
&lt;h3 id="1-poor-pivot-selection"&gt;1. Poor Pivot Selection&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Pitfall:&lt;/strong&gt; Consistently choosing a pivot that is either the smallest or largest element in the sub-array (e.g., always picking the first element in an already sorted array).
&lt;strong&gt;Consequence:&lt;/strong&gt; Degrades time complexity to &lt;code&gt;O(n^2)&lt;/code&gt;.
&lt;strong&gt;Avoidance:&lt;/strong&gt; Implement robust pivot selection strategies.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Random Pivot:&lt;/strong&gt; Select a random index within the sub-array and swap its element with the last element (if using Lomuto with last element pivot) or the first element (if using Hoare with first element pivot) before partitioning.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Median-of-Three:&lt;/strong&gt; Calculate the median of the first, middle, and last elements and use that as the pivot. This significantly reduces the chances of worst-case scenarios.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-stack-overflow"&gt;2. Stack Overflow&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Pitfall:&lt;/strong&gt; Deep recursion, especially in the &lt;code&gt;O(n^2)&lt;/code&gt; worst-case scenario, can lead to the call stack overflowing, causing a program crash.
&lt;strong&gt;Consequence:&lt;/strong&gt; &lt;code&gt;RecursionError&lt;/code&gt; in Python, or segmentation fault in C/C++.
&lt;strong&gt;Avoidance:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tail-Call Optimization:&lt;/strong&gt; Some languages and compilers can optimize tail-recursive calls, but Python does not.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Iterative Implementation:&lt;/strong&gt; Convert the recursive QuickSort into an iterative version using an explicit stack. This gives manual control over stack depth.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recurse on Smaller Sub-array First:&lt;/strong&gt; Always make the recursive call on the smaller of the two sub-arrays first. This ensures that the maximum depth of the recursion stack is &lt;code&gt;O(log n)&lt;/code&gt;, even in the worst theoretical partitioning, thus preventing stack overflow for typical limits.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hybrid Sorts (Introsort):&lt;/strong&gt; Use an introspective sort that switches to HeapSort if recursion depth gets too large.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-off-by-one-errors-in-partitioning"&gt;3. Off-by-One Errors in Partitioning&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Pitfall:&lt;/strong&gt; Incorrect indexing in the partition function, leading to infinite loops, elements being skipped, or array out-of-bounds errors.
&lt;strong&gt;Consequence:&lt;/strong&gt; Incorrectly sorted arrays, crashes, or infinite loops.
&lt;strong&gt;Avoidance:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Careful Index Management:&lt;/strong&gt; Double-check &lt;code&gt;low&lt;/code&gt;, &lt;code&gt;high&lt;/code&gt;, &lt;code&gt;i&lt;/code&gt;, and &lt;code&gt;j&lt;/code&gt; indices. Ensure loop conditions (&lt;code&gt;range(low, high)&lt;/code&gt; vs &lt;code&gt;range(low, high + 1)&lt;/code&gt;) and swap logic are precise.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Thorough Testing:&lt;/strong&gt; Test with edge cases: empty arrays, single-element arrays, two-element arrays, sorted arrays, reverse-sorted arrays, arrays with all identical elements.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visual Debugging:&lt;/strong&gt; Use a debugger to step through the &lt;code&gt;partition&lt;/code&gt; function with a small array to see how indices and elements change.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-inefficient-handling-of-duplicates"&gt;4. Inefficient Handling of Duplicates&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Pitfall:&lt;/strong&gt; Standard two-way partitioning can be inefficient if the array contains many identical elements, as they might be repeatedly compared and swapped.
&lt;strong&gt;Consequence:&lt;/strong&gt; Can approach &lt;code&gt;O(n^2)&lt;/code&gt; complexity in extreme cases (e.g., an array of all identical elements).
&lt;strong&gt;Avoidance:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Three-Way Partitioning:&lt;/strong&gt; Implement a three-way partition scheme (less than pivot, equal to pivot, greater than pivot). This groups all equal elements together in a single pass, preventing them from being processed in subsequent recursive calls.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;By anticipating these common pitfalls and employing the recommended avoidance strategies, developers can build more robust and efficient QuickSort implementations.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="conclusion-mastering-the-quicksort-algorithm"&gt;Conclusion: Mastering the QuickSort Algorithm&lt;/h2&gt;
&lt;p&gt;The journey through the QuickSort Algorithm Explained: A Step-by-Step Guide illuminates not just a sorting method, but a fundamental paradigm of efficient computation. From its elegant divide-and-conquer strategy to its nuanced pivot selection and partitioning schemes, QuickSort stands as a testament to intelligent algorithm design. Its average-case &lt;code&gt;O(n log n)&lt;/code&gt; performance, combined with its in-place nature and cache-friendliness, solidifies its position as a go-to choice for sorting large datasets in countless real-world applications and standard library implementations.&lt;/p&gt;
&lt;p&gt;While its &lt;code&gt;O(n^2)&lt;/code&gt; worst-case scenario demands careful consideration and intelligent optimizations like random pivots, median-of-three, or hybrid approaches like Introsort, its practical speed remains unmatched by many. Mastering QuickSort provides developers with a powerful tool in their algorithmic arsenal, enhancing their ability to build high-performance, memory-efficient software. This foundational understanding is crucial for tackling more complex challenges, such as those involving &lt;a href="/number-of-islands-graph-traversal-tutorial/"&gt;graph traversal algorithms&lt;/a&gt; or dynamic programming. Understanding its trade-offs against algorithms like MergeSort and HeapSort further refines one's ability to choose the right tool for the right job. By grasping the intricacies of the QuickSort Algorithm Explained: A Step-by-Step Guide, you gain a powerful tool for efficient data management and a deeper appreciation for the art of algorithm design.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the primary advantage of QuickSort?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: QuickSort is generally the fastest comparison-based sorting algorithm in practice for large datasets due to its excellent average-case O(n log n) performance, in-place nature, and cache-friendly data access patterns. This makes it a preferred choice for many real-world applications where speed is paramount.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is QuickSort's worst-case time complexity and why does it occur?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Its worst-case time complexity is O(n^2), which happens when the pivot consistently creates highly unbalanced partitions. This typically occurs when the input array is already sorted or reverse-sorted and the pivot is always chosen poorly (e.g., as the first or last element), leading to an imbalanced recursion tree.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Is QuickSort a stable sorting algorithm?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: No, QuickSort is generally not a stable sorting algorithm. This means it does not guarantee that the relative order of elements with equal values will be preserved after sorting, as swaps during partitioning can alter their original positions.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/quick-sort/"&gt;GeeksforGeeks - QuickSort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Quicksort"&gt;Wikipedia - Quicksort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.khanacademy.org/computing/computer-science/algorithms/quick-sort/a/overview-of-quicksort"&gt;Khan Academy - Quicksort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://mitpress.mit.edu/books/introduction-algorithms"&gt;Introduction to Algorithms (CLRS) - Chapter 7&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Competitive Programming"/><category term="Python"/><category term="Sorting Algorithms"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/quicksort-algorithm-explained-step-by-step-guide.webp" width="1200"/><media:title type="plain">QuickSort Algorithm Explained: A Step-by-Step Guide for Developers</media:title><media:description type="plain">Demystify the QuickSort Algorithm Explained: A Step-by-Step Guide for developers. Learn its mechanics, complexity, and practical applications in depth.</media:description></entry><entry><title>Demystifying Binary Trees: Structure, Traversal, &amp; Use Explained</title><link href="https://analyticsdrive.tech/demystifying-binary-trees-structure-traversal-use/" rel="alternate"/><published>2026-03-18T11:17:00+05:30</published><updated>2026-03-18T11:17:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-18:/demystifying-binary-trees-structure-traversal-use/</id><summary type="html">&lt;p&gt;Explore Demystifying Binary Trees: Structure, Traversal, &amp;amp; Use. This guide covers core concepts, traversal algorithms, and real-world applications in compute...&lt;/p&gt;</summary><content type="html">&lt;p&gt;To truly master efficient data organization and manipulation in computer science, understanding the &lt;strong&gt;structure&lt;/strong&gt; and &lt;strong&gt;use&lt;/strong&gt; of &lt;strong&gt;binary trees&lt;/strong&gt; is foundational, particularly their various &lt;strong&gt;traversal&lt;/strong&gt; methods. In the vast landscape of computer science, data structures are the blueprints that enable efficient data organization and manipulation. Among these, &lt;strong&gt;binary trees&lt;/strong&gt; stand out as particularly versatile and powerful tools. Their hierarchical nature allows for intuitive modeling of many real-world relationships, and their inherent structure supports highly optimized algorithms for searching, sorting, and data retrieval. This guide aims at &lt;strong&gt;Demystifying Binary Trees: Structure, Traversal, &amp;amp; Use&lt;/strong&gt; for the tech-savvy reader, breaking down their core concepts, exploring various traversal methods, and illustrating their widespread practical applications in modern computing. Understanding the fundamental structure and how to navigate these trees is paramount for anyone looking to deepen their grasp of algorithms and system design.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#demystifying-binary-trees-what-are-they"&gt;Demystifying Binary Trees: What Are They?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-fundamental-structure-of-binary-trees"&gt;The Fundamental Structure of Binary Trees&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#key-components-of-a-node"&gt;Key Components of a Node&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#tree-terminology"&gt;Tree Terminology&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#types-of-binary-trees-beyond-the-basics"&gt;Types of Binary Trees: Beyond the Basics&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#full-binary-tree"&gt;Full Binary Tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#complete-binary-tree"&gt;Complete Binary Tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#perfect-binary-tree"&gt;Perfect Binary Tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#skewed-binary-tree"&gt;Skewed Binary Tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#binary-search-tree-bst"&gt;Binary Search Tree (BST)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#self-balancing-binary-search-trees-avl-tree-red-black-tree"&gt;Self-Balancing Binary Search Trees (AVL Tree &amp;amp; Red-Black Tree)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#navigating-the-depths-binary-tree-traversal-methods"&gt;Navigating the Depths: Binary Tree Traversal Methods&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#depth-first-traversal-dft"&gt;Depth-First Traversal (DFT)&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#in-order-traversal-left-root-right"&gt;In-order Traversal (Left -&amp;gt; Root -&amp;gt; Right)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#pre-order-traversal-root-left-right"&gt;Pre-order Traversal (Root -&amp;gt; Left -&amp;gt; Right)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#post-order-traversal-left-right-root"&gt;Post-order Traversal (Left -&amp;gt; Right -&amp;gt; Root)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#breadth-first-traversal-bft-level-order-traversal"&gt;Breadth-First Traversal (BFT) / Level-Order Traversal&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-practical-use-of-binary-trees-in-computing"&gt;The Practical Use of Binary Trees in Computing&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#efficient-searching-and-sorting"&gt;Efficient Searching and Sorting&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#database-indexing"&gt;Database Indexing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#expression-parsers-compilers"&gt;Expression Parsers &amp;amp; Compilers&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#file-systems"&gt;File Systems&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#network-routing-algorithms"&gt;Network Routing Algorithms&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#decision-making-algorithms-aiml"&gt;Decision-Making Algorithms (AI/ML)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#advantages-and-disadvantages-of-using-binary-trees"&gt;Advantages and Disadvantages of Using Binary Trees&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#advantages"&gt;Advantages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#disadvantages"&gt;Disadvantages&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#optimizations-and-future-considerations"&gt;Optimizations and Future Considerations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion-the-enduring-relevance-of-demystifying-binary-trees"&gt;Conclusion: The Enduring Relevance of Demystifying Binary Trees&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="demystifying-binary-trees-what-are-they"&gt;Demystifying Binary Trees: What Are They?&lt;/h2&gt;
&lt;p&gt;At its core, a binary tree is a hierarchical data structure composed of nodes, where each node has at most two children, typically referred to as the "left child" and the "right child." This strict limitation of two children per node is what differentiates a binary tree from a general tree, which can have any number of children. The top-most node in a tree is called the "root," and it serves as the entry point to the entire structure. If a tree has no nodes, it is called a "null" or "empty" tree.&lt;/p&gt;
&lt;p&gt;Think of a binary tree like a simplified family tree where each person (node) can have at most two direct descendants. Or, consider an organizational chart where each manager (node) oversees at most two direct reports. This hierarchical arrangement allows for a logical flow of data, enabling operations that might be cumbersome with linear structures like arrays or linked lists. The importance of binary trees stems from their capacity to organize data in a way that significantly speeds up operations like searching, insertion, and deletion, often achieving logarithmic time complexity (O(log n)) in well-balanced scenarios, a stark improvement over the linear complexity (O(n)) often seen in other structures.&lt;/p&gt;
&lt;h2 id="the-fundamental-structure-of-binary-trees"&gt;The Fundamental Structure of Binary Trees&lt;/h2&gt;
&lt;p&gt;To truly grasp binary trees, it's essential to understand their basic building blocks and the terminology associated with their structure. Each binary tree is a collection of interconnected nodes, each holding a piece of data and references to its potential children.&lt;/p&gt;
&lt;h3 id="key-components-of-a-node"&gt;Key Components of a Node&lt;/h3&gt;
&lt;p&gt;Every node within a binary tree typically consists of three primary elements:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Data/Value:&lt;/strong&gt; This is the information that the node stores. It can be any type of data, such as an integer, a string, an object, or a pointer to more complex information.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Left Child Pointer:&lt;/strong&gt; A reference (or pointer) to another node, which represents the root of its left subtree. If a node has no left child, this pointer will typically be null.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Right Child Pointer:&lt;/strong&gt; A reference (or pointer) to another node, which represents the root of its right subtree. If a node has no right child, this pointer will typically be null.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Some implementations might also include a "parent pointer," which references the node's immediate parent. While not strictly necessary for all tree operations, a parent pointer can simplify certain traversal or modification tasks, especially when navigating upwards is required.&lt;/p&gt;
&lt;h3 id="tree-terminology"&gt;Tree Terminology&lt;/h3&gt;
&lt;p&gt;Understanding the specific vocabulary of tree structures is crucial for clear communication and deeper comprehension:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Root:&lt;/strong&gt; The single node at the very top of the tree. It has no parent. Every other node in the tree is a descendant of the root.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Parent:&lt;/strong&gt; A node that has one or more children. In the hierarchical structure, a parent node is directly above its child nodes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Child:&lt;/strong&gt; A node directly connected to another node when moving away from the root. A child node has exactly one parent.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Siblings:&lt;/strong&gt; Nodes that share the same parent. For instance, a node's left child and right child are siblings.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Leaf Node (or External Node):&lt;/strong&gt; A node that has no children. These nodes are at the "bottom" of the tree.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Internal Node:&lt;/strong&gt; Any node that is not a leaf node (i.e., it has at least one child).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edge:&lt;/strong&gt; The link or connection between two nodes. An edge represents a relationship (e.g., parent-child) between nodes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Path:&lt;/strong&gt; A sequence of connected nodes leading from one node to another. The length of a path is the number of edges along that path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Depth of a Node:&lt;/strong&gt; The number of edges from the root node to that specific node. The root node typically has a depth of 0.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Height of a Node:&lt;/strong&gt; The number of edges on the longest path from that node to a leaf node. Leaf nodes have a height of 0.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Height of a Tree:&lt;/strong&gt; The height of its root node. This represents the longest path from the root to any leaf in the tree.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Subtree:&lt;/strong&gt; A portion of a tree that is itself a tree. Any node in a tree can be considered the root of a subtree, comprising that node and all its descendants.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For example, consider a simple binary tree:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;      A
     / \
    B   C
   / \
  D   E
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Here, &lt;code&gt;A&lt;/code&gt; is the root. &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; are children of &lt;code&gt;A&lt;/code&gt;, and thus siblings. &lt;code&gt;D&lt;/code&gt; and &lt;code&gt;E&lt;/code&gt; are children of &lt;code&gt;B&lt;/code&gt;. &lt;code&gt;D&lt;/code&gt;, &lt;code&gt;E&lt;/code&gt;, and &lt;code&gt;C&lt;/code&gt; are leaf nodes. The depth of &lt;code&gt;A&lt;/code&gt; is 0, &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; is 1, and &lt;code&gt;D&lt;/code&gt; and &lt;code&gt;E&lt;/code&gt; is 2. The height of &lt;code&gt;D&lt;/code&gt;, &lt;code&gt;E&lt;/code&gt;, and &lt;code&gt;C&lt;/code&gt; is 0. The height of &lt;code&gt;B&lt;/code&gt; is 1 (longest path to &lt;code&gt;D&lt;/code&gt; or &lt;code&gt;E&lt;/code&gt;). The height of &lt;code&gt;A&lt;/code&gt; (the tree) is 2.&lt;/p&gt;
&lt;h2 id="types-of-binary-trees-beyond-the-basics"&gt;Types of Binary Trees: Beyond the Basics&lt;/h2&gt;
&lt;p&gt;While the fundamental structure of a binary tree remains consistent, various classifications exist based on how nodes are arranged and filled. These specific types are crucial because they dictate the efficiency and suitability of a binary tree for particular applications.&lt;/p&gt;
&lt;h3 id="full-binary-tree"&gt;Full Binary Tree&lt;/h3&gt;
&lt;p&gt;A full binary tree is defined by a simple rule: every node has either zero or two children. This means no node has only one child.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;All internal nodes have exactly two children.&lt;/li&gt;
&lt;li&gt;All leaf nodes have no children.&lt;/li&gt;
&lt;li&gt;A perfect binary tree (discussed below) is always a full binary tree.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="complete-binary-tree"&gt;Complete Binary Tree&lt;/h3&gt;
&lt;p&gt;A complete binary tree is a binary tree in which all levels are completely filled, except possibly the last level, and the last level must be filled from left to right. This structure is often represented using arrays for efficient storage without explicit pointers.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;All levels are completely filled, with the possible exception of the lowest level.&lt;/li&gt;
&lt;li&gt;Nodes in the lowest level are added as far left as possible.&lt;/li&gt;
&lt;li&gt;This property makes them suitable for heap implementations.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="perfect-binary-tree"&gt;Perfect Binary Tree&lt;/h3&gt;
&lt;p&gt;A perfect binary tree is a special type that is both a full binary tree and a complete binary tree. All internal nodes have two children, and all leaf nodes are at the same level (same depth).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;All internal nodes have two children.&lt;/li&gt;
&lt;li&gt;All leaf nodes are at the same depth.&lt;/li&gt;
&lt;li&gt;The number of nodes at depth &lt;code&gt;d&lt;/code&gt; is &lt;code&gt;2^d&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The total number of nodes in a perfect binary tree of height &lt;code&gt;h&lt;/code&gt; is &lt;code&gt;2^(h+1) - 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="skewed-binary-tree"&gt;Skewed Binary Tree&lt;/h3&gt;
&lt;p&gt;A skewed binary tree is a degenerate binary tree where all nodes have only one child, either always a left child or always a right child. This effectively makes the tree behave like a linked list, significantly degrading performance for operations that typically benefit from the tree's hierarchical structure.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Characteristics:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Left-Skewed:&lt;/strong&gt; Every node (except the leaves) has only a left child.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Right-Skewed:&lt;/strong&gt; Every node (except the leaves) has only a right child.&lt;/li&gt;
&lt;li&gt;Operations like search, insertion, and deletion in a skewed tree take O(n) time, similar to a linked list, rather than the desired O(log n) of a balanced tree.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="binary-search-tree-bst"&gt;Binary Search Tree (BST)&lt;/h3&gt;
&lt;p&gt;The Binary Search Tree (BST) is arguably the most common and important variant of the binary tree. It imposes a crucial ordering property on its nodes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;For any given node, all values in its left subtree are less than or equal to the node's value.&lt;/li&gt;
&lt;li&gt;All values in its right subtree are greater than the node's value.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This property enables highly efficient searching, insertion, and deletion operations, as each comparison at a node allows us to discard half of the remaining tree. On average, these operations take O(log n) time, making BSTs incredibly valuable for dynamic data management.&lt;/p&gt;
&lt;h3 id="self-balancing-binary-search-trees-avl-tree-red-black-tree"&gt;Self-Balancing Binary Search Trees (AVL Tree &amp;amp; Red-Black Tree)&lt;/h3&gt;
&lt;p&gt;While BSTs offer excellent average-case performance, their efficiency can degrade to O(n) in the worst-case scenario (e.g., when nodes are inserted in sorted order, creating a skewed tree). To counter this, self-balancing BSTs automatically adjust their structure (through rotations and re-coloring) to maintain a logarithmic height, thereby guaranteeing O(log n) time complexity for search, insertion, and deletion in all cases.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;AVL Tree:&lt;/strong&gt; One of the first self-balancing BSTs. It ensures that for every node, the heights of its left and right subtrees differ by at most 1.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Red-Black Tree:&lt;/strong&gt; Another widely used self-balancing BST, slightly less strict on balance than AVL trees, but often easier to implement. It maintains balance by ensuring specific properties related to node "colors" (red or black). Red-Black trees are used extensively in operating systems (e.g., Linux kernel's &lt;code&gt;map&lt;/code&gt; and &lt;code&gt;set&lt;/code&gt; implementations), databases, and Java's &lt;code&gt;TreeMap&lt;/code&gt; and &lt;code&gt;TreeSet&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="navigating-the-depths-binary-tree-traversal-methods"&gt;Navigating the Depths: Binary Tree Traversal Methods&lt;/h2&gt;
&lt;p&gt;Traversal refers to the process of visiting each node in a tree exactly once in a specific order. The way we traverse a binary tree dictates how its data is processed. There are two primary categories of traversal algorithms: Depth-First Traversal (DFT) and Breadth-First Traversal (BFT).&lt;/p&gt;
&lt;h3 id="depth-first-traversal-dft"&gt;Depth-First Traversal (DFT)&lt;/h3&gt;
&lt;p&gt;Depth-First Traversal explores as far as possible along each branch before backtracking. Imagine exploring a cave system: you go down one path as deep as you can, and only when you hit a dead end do you come back up to explore another path. DFT typically uses recursion or an explicit stack. There are three main ways to perform DFT:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In-order Traversal (Left -&amp;gt; Root -&amp;gt; Right)&lt;/li&gt;
&lt;li&gt;Pre-order Traversal (Root -&amp;gt; Left -&amp;gt; Right)&lt;/li&gt;
&lt;li&gt;Post-order Traversal (Left -&amp;gt; Right -&amp;gt; Root)&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="in-order-traversal-left-root-right"&gt;In-order Traversal (Left -&amp;gt; Root -&amp;gt; Right)&lt;/h4&gt;
&lt;p&gt;In-order traversal visits the left subtree first, then the current node (root), and finally the right subtree.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Use Case:&lt;/strong&gt; For a Binary Search Tree, in-order traversal yields the nodes' values in non-decreasing (sorted) order.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conceptual Algorithm:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Recursively traverse the left subtree.&lt;/li&gt;
&lt;li&gt;Visit the current node (e.g., print its data).&lt;/li&gt;
&lt;li&gt;Recursively traverse the right subtree.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Example (Recursive):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let's say we have the tree:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;      4
     / \
    2   5
   / \
  1   3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;inorder(4)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;inorder(2)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;inorder(1)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;inorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;1&lt;/code&gt;. (Output: 1)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;inorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;2&lt;/code&gt;. (Output: 2)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;inorder(3)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;inorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;3&lt;/code&gt;. (Output: 3)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;inorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;4&lt;/code&gt;. (Output: 4)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;inorder(5)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;inorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;5&lt;/code&gt;. (Output: 5)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;inorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt; 1 2 3 4 5&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Iterative Approach (using a stack):&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Initialize an empty stack and a &lt;code&gt;current&lt;/code&gt; node pointer to the root.&lt;/li&gt;
&lt;li&gt;Loop while &lt;code&gt;current&lt;/code&gt; is not null or the stack is not empty:&lt;ol&gt;
&lt;li&gt;While &lt;code&gt;current&lt;/code&gt; is not null:&lt;ol&gt;
&lt;li&gt;Push &lt;code&gt;current&lt;/code&gt; onto the stack.&lt;/li&gt;
&lt;li&gt;Move &lt;code&gt;current&lt;/code&gt; to &lt;code&gt;current.left&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Pop a node from the stack. This is the next node to visit.&lt;/li&gt;
&lt;li&gt;Visit the popped node.&lt;/li&gt;
&lt;li&gt;Move &lt;code&gt;current&lt;/code&gt; to the popped node's &lt;code&gt;right&lt;/code&gt; child.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 id="pre-order-traversal-root-left-right"&gt;Pre-order Traversal (Root -&amp;gt; Left -&amp;gt; Right)&lt;/h4&gt;
&lt;p&gt;Pre-order traversal visits the current node (root) first, then recursively traverses the left subtree, and finally the right subtree.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Use Case:&lt;/strong&gt; Useful for creating a copy of a tree, or for expressing prefix notation for arithmetic expressions.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conceptual Algorithm:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Visit the current node.&lt;/li&gt;
&lt;li&gt;Recursively traverse the left subtree.&lt;/li&gt;
&lt;li&gt;Recursively traverse the right subtree.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Example (Recursive) using the same tree:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;code&gt;preorder(4)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;Visit &lt;code&gt;4&lt;/code&gt;. (Output: 4)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(2)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;Visit &lt;code&gt;2&lt;/code&gt;. (Output: 2)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(1)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;Visit &lt;code&gt;1&lt;/code&gt;. (Output: 1)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(3)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;Visit &lt;code&gt;3&lt;/code&gt;. (Output: 3)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(5)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;Visit &lt;code&gt;5&lt;/code&gt;. (Output: 5)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;preorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt; 4 2 1 3 5&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Iterative Approach (using a stack):&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;If the root is null, return.&lt;/li&gt;
&lt;li&gt;Initialize an empty stack and push the root onto it.&lt;/li&gt;
&lt;li&gt;While the stack is not empty:&lt;ol&gt;
&lt;li&gt;Pop a node &lt;code&gt;u&lt;/code&gt; from the stack.&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;u&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;u&lt;/code&gt; has a right child, push &lt;code&gt;u.right&lt;/code&gt; onto the stack.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;u&lt;/code&gt; has a left child, push &lt;code&gt;u.left&lt;/code&gt; onto the stack.
&lt;em&gt;Note: Push right child first so left child is processed before it (LIFO).&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 id="post-order-traversal-left-right-root"&gt;Post-order Traversal (Left -&amp;gt; Right -&amp;gt; Root)&lt;/h4&gt;
&lt;p&gt;Post-order traversal visits the left subtree, then the right subtree, and finally the current node (root).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Use Case:&lt;/strong&gt; Used for deleting a tree (delete children before parent), or for expressing postfix notation for arithmetic expressions.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conceptual Algorithm:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Recursively traverse the left subtree.&lt;/li&gt;
&lt;li&gt;Recursively traverse the right subtree.&lt;/li&gt;
&lt;li&gt;Visit the current node.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Example (Recursive) using the same tree:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;code&gt;postorder(4)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;postorder(2)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;postorder(1)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;postorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;postorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;1&lt;/code&gt;. (Output: 1)&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;postorder(3)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;postorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;postorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;3&lt;/code&gt;. (Output: 3)&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;2&lt;/code&gt;. (Output: 2)&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;postorder(5)&lt;/code&gt;:&lt;ol&gt;
&lt;li&gt;&lt;code&gt;postorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;postorder(null)&lt;/code&gt; -&amp;gt; returns.&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;5&lt;/code&gt;. (Output: 5)&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;4&lt;/code&gt;. (Output: 4)&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt; 1 3 2 5 4&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Iterative Approach (using two stacks or a clever single stack):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Using two stacks (simpler to grasp):&lt;/em&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Initialize two empty stacks, &lt;code&gt;s1&lt;/code&gt; and &lt;code&gt;s2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Push the root onto &lt;code&gt;s1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;While &lt;code&gt;s1&lt;/code&gt; is not empty:&lt;ol&gt;
&lt;li&gt;Pop a node &lt;code&gt;u&lt;/code&gt; from &lt;code&gt;s1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Push &lt;code&gt;u&lt;/code&gt; onto &lt;code&gt;s2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;u&lt;/code&gt; has a left child, push &lt;code&gt;u.left&lt;/code&gt; onto &lt;code&gt;s1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;u&lt;/code&gt; has a right child, push &lt;code&gt;u.right&lt;/code&gt; onto &lt;code&gt;s1&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;While &lt;code&gt;s2&lt;/code&gt; is not empty, pop and visit nodes from &lt;code&gt;s2&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="breadth-first-traversal-bft-level-order-traversal"&gt;Breadth-First Traversal (BFT) / Level-Order Traversal&lt;/h3&gt;
&lt;p&gt;Breadth-First Traversal explores the tree level by level, visiting all nodes at the current depth before moving on to nodes at the next depth. Imagine exploring a building floor by floor. BFT typically uses a queue.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conceptual Algorithm:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create an empty queue.&lt;/li&gt;
&lt;li&gt;Enqueue the root node.&lt;/li&gt;
&lt;li&gt;While the queue is not empty:&lt;ol&gt;
&lt;li&gt;Dequeue a node &lt;code&gt;u&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Visit &lt;code&gt;u&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;u&lt;/code&gt; has a left child, enqueue &lt;code&gt;u.left&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;u&lt;/code&gt; has a right child, enqueue &lt;code&gt;u.right&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Example using the same tree:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;      4
     / \
    2   5
   / \
  1   3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt;Initialize queue: &lt;code&gt;[4]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;4&lt;/code&gt;. Visit &lt;code&gt;4&lt;/code&gt;. Enqueue &lt;code&gt;2&lt;/code&gt;, &lt;code&gt;5&lt;/code&gt;. Queue: &lt;code&gt;[2, 5]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;2&lt;/code&gt;. Visit &lt;code&gt;2&lt;/code&gt;. Enqueue &lt;code&gt;1&lt;/code&gt;, &lt;code&gt;3&lt;/code&gt;. Queue: &lt;code&gt;[5, 1, 3]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;5&lt;/code&gt;. Visit &lt;code&gt;5&lt;/code&gt;. Enqueue nothing. Queue: &lt;code&gt;[1, 3]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;1&lt;/code&gt;. Visit &lt;code&gt;1&lt;/code&gt;. Enqueue nothing. Queue: &lt;code&gt;[3]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;3&lt;/code&gt;. Visit &lt;code&gt;3&lt;/code&gt;. Enqueue nothing. Queue: &lt;code&gt;[]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Queue is empty, traversal complete.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt; 4 2 5 1 3&lt;/p&gt;
&lt;h2 id="the-practical-use-of-binary-trees-in-computing"&gt;The Practical Use of Binary Trees in Computing&lt;/h2&gt;
&lt;p&gt;Binary trees are not merely theoretical constructs; they are fundamental data structures with ubiquitous applications across various domains of computer science and technology. Their ability to efficiently organize and retrieve data makes them indispensable.&lt;/p&gt;
&lt;h3 id="efficient-searching-and-sorting"&gt;Efficient Searching and Sorting&lt;/h3&gt;
&lt;p&gt;This is perhaps the most classic application. Binary Search Trees (BSTs), and especially their self-balancing variants (AVL, Red-Black Trees), allow for data to be stored in an ordered fashion, enabling average-case &lt;code&gt;O(log n)&lt;/code&gt; time complexity for searching, insertion, and deletion operations. This efficiency is critical in scenarios where data is frequently updated and queried. For example, a dictionary or an associative array (map) can be implemented using a BST to achieve fast lookups, much like how you might approach optimizing solutions in &lt;a href="/839-similar-string-groups-leetcode-python-cpp-java-tutorial/"&gt;competitive programming challenges&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Furthermore, a specific type of binary tree called a "heap" (typically a binary heap) is the backbone of priority queues and the efficient Heap Sort algorithm. Priority queues are essential in operating systems for scheduling tasks, in network routing protocols, and in various &lt;a href="/number-of-islands-graph-traversal-tutorial/"&gt;graph algorithms&lt;/a&gt; like Dijkstra's or Prim's.&lt;/p&gt;
&lt;h3 id="database-indexing"&gt;Database Indexing&lt;/h3&gt;
&lt;p&gt;While not strictly binary trees, B-trees and B+ trees are generalized tree data structures that are descendants of binary tree concepts and are extensively used in database management systems (DBMS) for indexing. They are designed to efficiently handle large amounts of data stored on disk, minimizing disk I/O operations. A B-tree, for instance, can have more than two children per node, but it maintains a balanced structure that ensures fast &lt;code&gt;O(log n)&lt;/code&gt; search, insertion, and deletion times, even for vast datasets. This is how your SQL queries execute rapidly, even on tables with millions of records.&lt;/p&gt;
&lt;h3 id="expression-parsers-compilers"&gt;Expression Parsers &amp;amp; Compilers&lt;/h3&gt;
&lt;p&gt;In the realm of programming language processing, binary trees are crucial for representing and evaluating arithmetic and logical expressions. Compilers often convert source code into an Abstract Syntax Tree (AST), which is frequently a binary tree where internal nodes represent operations (like &lt;code&gt;+&lt;/code&gt;, &lt;code&gt;-&lt;/code&gt;, &lt;code&gt;*&lt;/code&gt;) and leaf nodes represent operands (variables or literals). This tree structure makes it straightforward to parse, analyze, and optimize the code before execution.&lt;/p&gt;
&lt;p&gt;Consider the expression &lt;code&gt;(A + B) * C&lt;/code&gt;. It can be represented as a binary tree:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;      *
     / \
    +   C
   / \
  A   B
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Traversals like post-order can then be used to generate postfix notation or evaluate the expression.&lt;/p&gt;
&lt;h3 id="file-systems"&gt;File Systems&lt;/h3&gt;
&lt;p&gt;The hierarchical structure of file systems (directories and files) can be naturally modeled as a tree. While often a general tree (directories can contain many files/subdirectories), the underlying principles of tree traversal and management apply. Concepts like depth-first search are used when searching for files or calculating directory sizes.&lt;/p&gt;
&lt;h3 id="network-routing-algorithms"&gt;Network Routing Algorithms&lt;/h3&gt;
&lt;p&gt;In computer networks, tree structures, particularly spanning trees, are vital for routing and managing network topology. Algorithms like the Spanning Tree Protocol (STP) in Ethernet networks prevent network loops by creating a logical tree structure from a mesh topology. This ensures efficient data packet delivery and avoids broadcast storms.&lt;/p&gt;
&lt;h3 id="decision-making-algorithms-aiml"&gt;Decision-Making Algorithms (AI/ML)&lt;/h3&gt;
&lt;p&gt;Decision Trees are a fundamental supervised machine learning algorithm used for classification and regression tasks. These trees are effectively binary (or sometimes multi-way) trees where each internal node represents a "decision" or test on an attribute, each branch represents the outcome of the test, and each leaf node represents a class label (in classification) or a numerical value (in regression). They provide an intuitive and interpretable model for making predictions, aligning with the broader trends in &lt;a href="/latest-ai-technologies-shaping-future/"&gt;latest AI technologies&lt;/a&gt;. For instance, a decision tree might classify whether a customer will churn based on their age, usage patterns, and past interactions, making a series of binary decisions down the tree.&lt;/p&gt;
&lt;h2 id="advantages-and-disadvantages-of-using-binary-trees"&gt;Advantages and Disadvantages of Using Binary Trees&lt;/h2&gt;
&lt;p&gt;Like any data structure, binary trees come with their own set of strengths and weaknesses that dictate their suitability for different applications.&lt;/p&gt;
&lt;h3 id="advantages"&gt;Advantages&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Efficient Data Organization and Retrieval:&lt;/strong&gt; For balanced binary search trees, operations like search, insertion, and deletion have an average time complexity of O(log n). This makes them highly efficient for managing dynamic datasets where these operations are frequent. Compared to O(n) for linked lists or arrays for similar operations, this is a significant performance boost for large &lt;code&gt;n&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Flexibility and Dynamic Resizing:&lt;/strong&gt; Unlike arrays, which have a fixed size or require expensive reallocations, trees can grow and shrink dynamically as elements are added or removed, making them suitable for situations where data volume is unpredictable.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hierarchical Representation:&lt;/strong&gt; Binary trees naturally represent hierarchical relationships, making them ideal for modeling structures like file systems, organizational charts, and abstract syntax trees in compilers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Basis for Advanced Structures:&lt;/strong&gt; Many complex and highly optimized data structures, such as heaps, B-trees, and self-balancing BSTs (AVL, Red-Black trees), are built upon the fundamental principles of binary trees. Understanding binary trees is a prerequisite for grasping these advanced concepts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ordered Data Retrieval:&lt;/strong&gt; In-order traversal of a BST provides data in a sorted order, which is a powerful property for many applications requiring sorted output.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="disadvantages"&gt;Disadvantages&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Worst-Case Performance Degradation:&lt;/strong&gt; Without proper balancing mechanisms, a binary search tree can degenerate into a skewed tree (resembling a linked list) if elements are inserted in a sorted or reverse-sorted order. In this worst-case scenario, operations that should be O(log n) become O(n), severely impacting performance. This necessitates the use of more complex self-balancing trees (AVL, Red-Black) in production systems, which adds implementation overhead.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory Overhead:&lt;/strong&gt; Each node in a binary tree typically stores not only the data but also at least two pointers (to left and right children). This pointer overhead can be substantial, especially for small data types, leading to higher memory consumption compared to contiguous data structures like arrays.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Complex Implementation:&lt;/strong&gt; Implementing binary trees, particularly self-balancing ones, is more complex than simpler linear data structures like arrays or linked lists. Managing pointers, rotations, and color properties requires careful attention to detail and can be prone to errors.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not Ideal for Sequential Access:&lt;/strong&gt; While trees excel at random access (via search), accessing elements sequentially (like iterating through all elements in memory order) can be less efficient than with arrays due to scattered memory locations (unless specifically designed for cache-friendliness, which B-trees attempt to do for disk access).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deletion Complexity:&lt;/strong&gt; Deleting a node from a binary search tree, especially one with two children, can be a non-trivial operation, requiring careful rearrangement to maintain the BST property.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="optimizations-and-future-considerations"&gt;Optimizations and Future Considerations&lt;/h2&gt;
&lt;p&gt;The journey of binary trees doesn't end with their basic definitions. Continuous research and development focus on optimizing their performance and exploring new applications. Self-balancing binary search trees (like AVL and Red-Black trees) are a testament to this, solving the crucial problem of worst-case performance degradation by automatically restructuring the tree. Their pervasive use in language libraries and operating system kernels highlights their enduring importance in ensuring predictable, efficient data management.&lt;/p&gt;
&lt;p&gt;For disk-based data storage, B-trees and B+ trees represent significant advancements. These structures are optimized to minimize disk I/O operations by storing multiple keys per node, making them highly effective for database indexing and file systems where data locality and block reading are critical.&lt;/p&gt;
&lt;p&gt;Looking forward, the interaction of binary trees with emerging paradigms like parallel and distributed computing is an active area of research. How can tree operations be efficiently parallelized across multiple processors? What are the implications for tree structures in highly distributed environments? Furthermore, while nascent, the field of quantum computing presents an intriguing challenge and opportunity. Could quantum algorithms offer exponentially faster ways to traverse or search tree-like structures, potentially revolutionizing areas dependent on classical tree optimizations? These questions continue to drive innovation in this fundamental area of computer science.&lt;/p&gt;
&lt;h2 id="conclusion-the-enduring-relevance-of-demystifying-binary-trees"&gt;Conclusion: The Enduring Relevance of Demystifying Binary Trees&lt;/h2&gt;
&lt;p&gt;Binary trees, in their various forms, remain a cornerstone of computer science, offering an elegant solution for organizing and managing hierarchical data. From the fundamental concepts of nodes and edges to the intricate logic of traversal algorithms and the practical use cases in databases, compilers, and machine learning, their influence is profound and widespread. By &lt;strong&gt;Demystifying Binary Trees: Structure, Traversal, &amp;amp; Use&lt;/strong&gt;, we gain a deeper appreciation for the architectural elegance and computational power these data structures bring to the digital world. Their continued evolution and adaptation ensure they will remain a vital component in the toolkit of any technologist for years to come. Mastering binary trees is not just an academic exercise; it's a critical step towards building more efficient, robust, and scalable software systems.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the main difference between a binary tree and a general tree?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A binary tree limits each node to having at most two children (a left and a right child). A general tree, however, allows nodes to have any number of children, making it a more flexible but potentially less structured hierarchy.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: When should I use a self-balancing binary search tree over a regular binary search tree?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: You should use a self-balancing BST (like AVL or Red-Black trees) when you need guaranteed O(log n) performance for search, insertion, and deletion operations. Regular BSTs can degenerate to O(n) in worst-case scenarios, which self-balancing trees prevent by automatically adjusting their structure.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What are the primary types of binary tree traversals and their applications?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The primary traversals are In-order (sorted data in BSTs), Pre-order (copying trees, prefix expressions), Post-order (deleting trees, postfix expressions), and Level-order (breadth-first, processing by depth). Each serves specific purposes in data processing.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Binary_tree"&gt;Binary Tree - Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/introduction-to-binary-tree-data-structure-and-algorithm-tutorials/"&gt;Introduction to Binary Tree - GeeksforGeeks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://web.stanford.edu/class/cs107/lectures/20/BinarySearchTrees.pdf"&gt;Binary Search Tree - Stanford University&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://algs4.cs.princeton.edu/32bst/"&gt;Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Competitive Programming"/><category term="Technology"/><category term="Problem Solving"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/demystifying-binary-trees-structure-traversal-use.webp" width="1200"/><media:title type="plain">Demystifying Binary Trees: Structure, Traversal, &amp; Use Explained</media:title><media:description type="plain">Explore Demystifying Binary Trees: Structure, Traversal, &amp; Use. This guide covers core concepts, traversal algorithms, and real-world applications in compute...</media:description></entry><entry><title>839 Similar String Groups LeetCode: Python, C++, Java Solutions</title><link href="https://analyticsdrive.tech/839-similar-string-groups-leetcode-python-cpp-java-tutorial/" rel="alternate"/><published>2026-03-12T16:37:00+05:30</published><updated>2026-03-12T16:37:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-12:/839-similar-string-groups-leetcode-python-cpp-java-tutorial/</id><summary type="html">&lt;p&gt;Solve LeetCode 839 Similar String Groups effectively. This tutorial provides comprehensive solutions in Python, C++, and Java using Disjoint Set Union (DSU) ...&lt;/p&gt;</summary><content type="html">&lt;p&gt;The LeetCode problem 839 Similar String Groups challenges us to find the number of distinct groups of strings where two strings belong to the same group if they are "similar" (can be made identical by swapping exactly two characters) or if they are transitively similar. This comprehensive tutorial will guide you through solving the 839 Similar String Groups leetcode question in python, C++, java, detailing the underlying algorithms and providing complete code implementations. You'll learn how to leverage the Disjoint Set Union (DSU) data structure to efficiently tackle this grouping problem, understanding its core concepts, practical application, and performance considerations across multiple programming languages.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#understanding-the-problem-839-similar-string-groups"&gt;Understanding the Problem: 839 Similar String Groups&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#prerequisites-graph-theory-and-disjoint-set-union-dsu"&gt;Prerequisites: Graph Theory and Disjoint Set Union (DSU)&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#graph-representation"&gt;Graph Representation:&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#what-is-disjoint-set-union-dsu"&gt;What is Disjoint Set Union (DSU)?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-algorithm-steps-for-839-similar-string-groups"&gt;Core Algorithm Steps for 839 Similar String Groups&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-initialize-disjoint-set-union-dsu-structure"&gt;1. Initialize Disjoint Set Union (DSU) Structure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-iterate-through-all-pairs-of-strings"&gt;2. Iterate Through All Pairs of Strings&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-check-for-similarity-between-string-pairs"&gt;3. Check for Similarity Between String Pairs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-perform-union-operation-if-similar"&gt;4. Perform Union Operation if Similar&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-count-distinct-parents-or-num_groups-counter"&gt;5. Count Distinct Parents (or num_groups counter)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-the-solution-python"&gt;Implementing the Solution: Python&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#helper-function-aresimilars1-s2"&gt;Helper Function: areSimilar(s1, s2)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#dsu-class-in-python"&gt;DSU Class in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#main-solution-logic-for-839-similar-string-groups"&gt;Main Solution Logic for 839 Similar String Groups&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-time-and-space-complexity-analysis"&gt;Python Time and Space Complexity Analysis&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-the-solution-c"&gt;Implementing the Solution: C++&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#helper-function-aresimilarstring-s1-string-s2"&gt;Helper Function: areSimilar(string&amp;amp; s1, string&amp;amp; s2)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#dsu-class-in-c"&gt;DSU Class in C++&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#main-solution-logic-for-839-similar-string-groups_1"&gt;Main Solution Logic for 839 Similar String Groups&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#c-time-and-space-complexity-analysis"&gt;C++ Time and Space Complexity Analysis&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-the-solution-java"&gt;Implementing the Solution: Java&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#helper-function-aresimilarstring-s1-string-s2_1"&gt;Helper Function: areSimilar(String s1, String s2)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#dsu-class-in-java"&gt;DSU Class in Java&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#main-solution-logic-for-839-similar-string-groups_2"&gt;Main Solution Logic for 839 Similar String Groups&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#java-time-and-space-complexity-analysis"&gt;Java Time and Space Complexity Analysis&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-pitfalls-and-considerations"&gt;Common Pitfalls and Considerations&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-optimizations-and-advanced-topics"&gt;Further Optimizations and Advanced Topics&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#handling-larger-n-number-of-strings"&gt;Handling Larger N (Number of Strings)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#trie-based-optimization"&gt;Trie-based Optimization&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id="understanding-the-problem-839-similar-string-groups"&gt;Understanding the Problem: 839 Similar String Groups&lt;/h2&gt;
&lt;p&gt;The problem 839 Similar String Groups asks us to count the number of distinct groups among a given list of strings. The core definition revolves around "similarity." Two strings are considered similar if we can swap exactly two characters in one of the strings to make it equal to the other. Importantly, similarity is transitive: if string &lt;code&gt;A&lt;/code&gt; is similar to &lt;code&gt;B&lt;/code&gt;, and &lt;code&gt;B&lt;/code&gt; is similar to &lt;code&gt;C&lt;/code&gt;, then &lt;code&gt;A&lt;/code&gt;, &lt;code&gt;B&lt;/code&gt;, and &lt;code&gt;C&lt;/code&gt; all belong to the same group. All strings in the input array &lt;code&gt;strs&lt;/code&gt; have the same length.&lt;/p&gt;
&lt;p&gt;Let's break down the key aspects:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;String Length:&lt;/strong&gt; All strings in the input array &lt;code&gt;strs&lt;/code&gt; will have the same length. This is a crucial constraint that simplifies comparisons.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Similarity Definition:&lt;/strong&gt; Two strings, &lt;code&gt;s1&lt;/code&gt; and &lt;code&gt;s2&lt;/code&gt;, are similar if:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;They are identical (&lt;code&gt;s1 == s2&lt;/code&gt;). In this case, zero swaps are needed, which can be interpreted as swapping two identical characters.&lt;/li&gt;
&lt;li&gt;They differ by exactly two characters, and those two differing characters can be swapped to make the strings identical. For example, "abc" and "bac" are similar (swap 'a' and 'b'). "ab" and "ba" are similar. "abc" and "bca" are &lt;em&gt;not&lt;/em&gt; similar because it would require more than one swap to transform "abc" into "bca" (e.g., 'a' to 'b', 'b' to 'c', 'c' to 'a' - a cyclic shift, not a single swap).&lt;/li&gt;
&lt;li&gt;Consider "abac" and "aabc". Differing positions are index 1 ('b' vs 'a') and index 2 ('a' vs 'b'). If we swap 'b' and 'a' at these positions, "abac" becomes "aabc". So, they are similar.&lt;/li&gt;
&lt;li&gt;Consider "abcde" and "abxye". Differing positions are index 2 ('c' vs 'x') and index 3 ('d' vs 'y'). If we swap 'c' and 'd' in "abcde", it becomes "abdce". This is not "abxye". These are not similar.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Transitivity:&lt;/strong&gt; This is the hallmark of grouping problems. If A is similar to B, and B is similar to C, then A, B, and C all belong to the same group. This forms equivalence classes, which are perfectly suited for a Disjoint Set Union (DSU) data structure.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Example Scenarios:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let's look at some examples to clarify similarity:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;s1 = "tars"&lt;/code&gt;, &lt;code&gt;s2 = "rats"&lt;/code&gt;:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Differences: &lt;code&gt;s1[0]&lt;/code&gt; ('t') vs &lt;code&gt;s2[0]&lt;/code&gt; ('r'), &lt;code&gt;s1[1]&lt;/code&gt; ('a') vs &lt;code&gt;s2[1]&lt;/code&gt; ('a'), &lt;code&gt;s1[2]&lt;/code&gt; ('r') vs &lt;code&gt;s2[2]&lt;/code&gt; ('t'), &lt;code&gt;s1[3]&lt;/code&gt; ('s') vs &lt;code&gt;s2[3]&lt;/code&gt; ('s').&lt;/li&gt;
&lt;li&gt;Differing characters are 't' at index 0 and 'r' at index 2 in &lt;code&gt;s1&lt;/code&gt;, and 'r' at index 0 and 't' at index 2 in &lt;code&gt;s2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If we swap &lt;code&gt;s1[0]&lt;/code&gt; and &lt;code&gt;s1[2]&lt;/code&gt; ('t' and 'r'), &lt;code&gt;s1&lt;/code&gt; becomes "rats". They are similar.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;s1 = "love"&lt;/code&gt;, &lt;code&gt;s2 = "evil"&lt;/code&gt;:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Differences: All four characters are different. This would require more than one swap to make them identical (or rather, the characters at the differing positions are not a simple two-way swap). Not similar.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;s1 = "abc"&lt;/code&gt;, &lt;code&gt;s2 = "abc"&lt;/code&gt;:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;No differences. They are identical, thus similar.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The goal is to count how many such independent "groups" or "connected components" exist after considering all possible similar pairs.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="prerequisites-graph-theory-and-disjoint-set-union-dsu"&gt;Prerequisites: Graph Theory and Disjoint Set Union (DSU)&lt;/h2&gt;
&lt;p&gt;This problem, at its core, is a &lt;a href="/number-of-islands-graph-traversal-tutorial/"&gt;graph problem&lt;/a&gt;. Each string can be thought of as a node in a graph. An edge exists between two nodes (strings) if they are similar. Since similarity is transitive, this problem asks us to count the number of connected components in this implicitly defined graph. The most efficient data structure for solving connected components problems, especially when edges are added dynamically, is the &lt;a href="/find-all-people-with-secret-leetcode-2092-tutorial/"&gt;Disjoint Set Union (DSU)&lt;/a&gt;, also known as Union-Find.&lt;/p&gt;
&lt;h3 id="graph-representation"&gt;Graph Representation:&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Vertices:&lt;/strong&gt; Each unique string in the input array &lt;code&gt;strs&lt;/code&gt; is a vertex. If there are &lt;code&gt;N&lt;/code&gt; strings, there are &lt;code&gt;N&lt;/code&gt; vertices.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Edges:&lt;/strong&gt; An undirected edge exists between two vertices &lt;code&gt;strs[i]&lt;/code&gt; and &lt;code&gt;strs[j]&lt;/code&gt; if &lt;code&gt;strs[i]&lt;/code&gt; and &lt;code&gt;strs[j]&lt;/code&gt; are similar.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Goal:&lt;/strong&gt; Count the number of connected components in this graph.&lt;/p&gt;
&lt;h3 id="what-is-disjoint-set-union-dsu"&gt;What is Disjoint Set Union (DSU)?&lt;/h3&gt;
&lt;p&gt;DSU is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets. It provides two primary operations:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;find(element)&lt;/code&gt;:&lt;/strong&gt; Determines which subset a particular element belongs to. It returns a "representative" (or "root") of that element's subset.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;union(element1, element2)&lt;/code&gt;:&lt;/strong&gt; Merges the subsets containing &lt;code&gt;element1&lt;/code&gt; and &lt;code&gt;element2&lt;/code&gt; into a single subset.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;DSU is typically implemented using an array, &lt;code&gt;parent&lt;/code&gt;, where &lt;code&gt;parent[i]&lt;/code&gt; stores the parent of element &lt;code&gt;i&lt;/code&gt;. If &lt;code&gt;parent[i] == i&lt;/code&gt;, then &lt;code&gt;i&lt;/code&gt; is the root of its set.&lt;/p&gt;
&lt;p&gt;To optimize DSU for better performance, two heuristics are commonly used:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Path Compression (for &lt;code&gt;find&lt;/code&gt; operation):&lt;/strong&gt;
    When &lt;code&gt;find&lt;/code&gt; is called on an element &lt;code&gt;i&lt;/code&gt;, it traverses up the &lt;code&gt;parent&lt;/code&gt; array until it reaches the root. Path compression modifies the &lt;code&gt;parent&lt;/code&gt; array during this traversal. As it goes up, it makes every node it visits point directly to the root. This flattens the tree structure, making future &lt;code&gt;find&lt;/code&gt; operations on these nodes much faster.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Algorithm for &lt;code&gt;find(i)&lt;/code&gt; with Path Compression:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;If &lt;code&gt;parent[i] == i&lt;/code&gt;, then &lt;code&gt;i&lt;/code&gt; is the root; return &lt;code&gt;i&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Otherwise, set &lt;code&gt;parent[i] = find(parent[i])&lt;/code&gt; (recursively find the root and update the current node's parent).&lt;/li&gt;
&lt;li&gt;Return &lt;code&gt;parent[i]&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Union by Rank or Size (for &lt;code&gt;union&lt;/code&gt; operation):&lt;/strong&gt;
    To keep the trees flat and balanced, when performing a &lt;code&gt;union&lt;/code&gt; operation, we attach the root of the smaller tree to the root of the larger tree. This prevents skewed trees that could degrade performance.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Union by Rank:&lt;/strong&gt; &lt;code&gt;rank[i]&lt;/code&gt; stores an upper bound on the height of the tree rooted at &lt;code&gt;i&lt;/code&gt;. When merging two trees, the tree with the smaller rank is attached to the root of the tree with the larger rank. If ranks are equal, one is arbitrarily chosen as the new root, and its rank is incremented.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Union by Size:&lt;/strong&gt; &lt;code&gt;size[i]&lt;/code&gt; stores the total number of nodes in the tree rooted at &lt;code&gt;i&lt;/code&gt;. When merging, the tree with fewer nodes is attached to the root of the tree with more nodes. The size of the new root is updated by summing the sizes of the two merged trees. Union by size is often slightly simpler to implement and provides similar performance benefits.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Algorithm for &lt;code&gt;union(i, j)&lt;/code&gt; with Union by Size:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Find the roots of &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;j&lt;/code&gt;: &lt;code&gt;root_i = find(i)&lt;/code&gt;, &lt;code&gt;root_j = find(j)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;root_i != root_j&lt;/code&gt; (meaning they are in different sets):&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;size[root_i] &amp;lt; size[root_j]&lt;/code&gt;, swap &lt;code&gt;root_i&lt;/code&gt; and &lt;code&gt;root_j&lt;/code&gt; to ensure &lt;code&gt;root_i&lt;/code&gt; always points to the larger set's root.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;parent[root_j] = root_i&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Update &lt;code&gt;size[root_i] += size[root_j]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Return &lt;code&gt;true&lt;/code&gt; (sets were merged).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Else (&lt;code&gt;root_i == root_j&lt;/code&gt;): Return &lt;code&gt;false&lt;/code&gt; (they were already in the same set).&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Why DSU for this problem?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The problem asks for groups, which are essentially connected components. We iterate through all pairs of strings. If two strings are similar, we "union" their respective sets. After checking all pairs, the number of disjoint sets remaining will be the number of similar string groups. DSU efficiently manages these merges and queries for set membership. The optimized DSU operations (path compression and union by rank/size) provide nearly constant time complexity on average for &lt;code&gt;find&lt;/code&gt; and &lt;code&gt;union&lt;/code&gt; operations (specifically, &lt;code&gt;O(alpha(N))&lt;/code&gt; where &lt;code&gt;alpha&lt;/code&gt; is the inverse Ackermann function, which grows extremely slowly, practically constant for any realistic &lt;code&gt;N&lt;/code&gt;).&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="core-algorithm-steps-for-839-similar-string-groups"&gt;Core Algorithm Steps for 839 Similar String Groups&lt;/h2&gt;
&lt;p&gt;To solve the 839 Similar String Groups problem using DSU, we follow these steps:&lt;/p&gt;
&lt;h3 id="1-initialize-disjoint-set-union-dsu-structure"&gt;1. Initialize Disjoint Set Union (DSU) Structure&lt;/h3&gt;
&lt;p&gt;We start by initializing a DSU structure for &lt;code&gt;N&lt;/code&gt; strings, where &lt;code&gt;N&lt;/code&gt; is the number of strings in the input array &lt;code&gt;strs&lt;/code&gt;. Each string initially belongs to its own unique set.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;parent&lt;/code&gt; array: &lt;code&gt;parent[i] = i&lt;/code&gt; for all &lt;code&gt;i&lt;/code&gt; from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;N-1&lt;/code&gt;. This means each element is its own root.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;size&lt;/code&gt; array (for union by size optimization): &lt;code&gt;size[i] = 1&lt;/code&gt; for all &lt;code&gt;i&lt;/code&gt;. Each set initially contains one element.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;num_groups&lt;/code&gt;: Initialize this counter to &lt;code&gt;N&lt;/code&gt;, as initially, every string forms its own group. This counter will decrement each time a successful &lt;code&gt;union&lt;/code&gt; operation merges two distinct groups.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-iterate-through-all-pairs-of-strings"&gt;2. Iterate Through All Pairs of Strings&lt;/h3&gt;
&lt;p&gt;We need to check every possible pair of strings to determine if they are similar. Since similarity is symmetric (&lt;code&gt;s1&lt;/code&gt; similar to &lt;code&gt;s2&lt;/code&gt; implies &lt;code&gt;s2&lt;/code&gt; similar to &lt;code&gt;s1&lt;/code&gt;), we only need to check each pair once.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Use nested loops: Outer loop &lt;code&gt;i&lt;/code&gt; from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;N-1&lt;/code&gt;, inner loop &lt;code&gt;j&lt;/code&gt; from &lt;code&gt;i+1&lt;/code&gt; to &lt;code&gt;N-1&lt;/code&gt;. This ensures each unique pair &lt;code&gt;(strs[i], strs[j])&lt;/code&gt; is considered exactly once.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-check-for-similarity-between-string-pairs"&gt;3. Check for Similarity Between String Pairs&lt;/h3&gt;
&lt;p&gt;For each pair &lt;code&gt;(strs[i], strs[j])&lt;/code&gt;, we need a helper function, let's call it &lt;code&gt;areSimilar(s1, s2)&lt;/code&gt;, that returns &lt;code&gt;true&lt;/code&gt; if the strings are similar according to the problem's definition, and &lt;code&gt;false&lt;/code&gt; otherwise.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;areSimilar(s1, s2)&lt;/code&gt; Logic:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initial check:&lt;/strong&gt; If &lt;code&gt;s1.length() != s2.length()&lt;/code&gt;, they cannot be similar. (Though the problem states all strings have the same length, it's good practice).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Count differences:&lt;/strong&gt; Iterate through both strings, character by character. Store the indices where characters differ. Let's say these indices are stored in a list &lt;code&gt;diff_indices&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Analyze &lt;code&gt;diff_indices&lt;/code&gt;:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;diff_indices&lt;/code&gt; is empty: The strings are identical. They are similar. Return &lt;code&gt;true&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;diff_indices.size()&lt;/code&gt; is 2: This is the critical case. Let the differing indices be &lt;code&gt;idx1&lt;/code&gt; and &lt;code&gt;idx2&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Check if &lt;code&gt;s1[idx1] == s2[idx2]&lt;/code&gt; AND &lt;code&gt;s1[idx2] == s2[idx1]&lt;/code&gt;. This condition confirms that swapping &lt;code&gt;s1[idx1]&lt;/code&gt; and &lt;code&gt;s1[idx2]&lt;/code&gt; (or &lt;code&gt;s2[idx1]&lt;/code&gt; and &lt;code&gt;s2[idx2]&lt;/code&gt;) would make the strings identical. If this holds, they are similar. Return &lt;code&gt;true&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;In any other case (&lt;code&gt;diff_indices.size()&lt;/code&gt; is 1 or greater than 2): They are not similar. Return &lt;code&gt;false&lt;/code&gt;. A single difference means one character needs to change, not a swap. More than two differences means more than one swap is needed.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="4-perform-union-operation-if-similar"&gt;4. Perform Union Operation if Similar&lt;/h3&gt;
&lt;p&gt;If &lt;code&gt;areSimilar(strs[i], strs[j])&lt;/code&gt; returns &lt;code&gt;true&lt;/code&gt;, it means &lt;code&gt;strs[i]&lt;/code&gt; and &lt;code&gt;strs[j]&lt;/code&gt; belong to the same group. We then perform a &lt;code&gt;union(i, j)&lt;/code&gt; operation on our DSU structure.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;union&lt;/code&gt; operation will merge the sets containing &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;j&lt;/code&gt;. If they were already in the same set, &lt;code&gt;union&lt;/code&gt; does nothing (or returns &lt;code&gt;false&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;If they were in different sets and are now merged, the &lt;code&gt;union&lt;/code&gt; operation effectively reduces the total number of disjoint groups by one. This is where &lt;code&gt;num_groups&lt;/code&gt; is decremented.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-count-distinct-parents-or-num_groups-counter"&gt;5. Count Distinct Parents (or &lt;code&gt;num_groups&lt;/code&gt; counter)&lt;/h3&gt;
&lt;p&gt;After iterating through all pairs and performing &lt;code&gt;union&lt;/code&gt; operations where necessary, the &lt;code&gt;num_groups&lt;/code&gt; counter will hold the final count of distinct similar string groups. This is because each &lt;code&gt;union&lt;/code&gt; operation on previously distinct sets correctly decrements the count of total groups.&lt;/p&gt;
&lt;p&gt;Alternatively, if not using a &lt;code&gt;num_groups&lt;/code&gt; counter during &lt;code&gt;union&lt;/code&gt;, you can iterate through the &lt;code&gt;parent&lt;/code&gt; array at the end and count how many elements are their own parents (&lt;code&gt;parent[i] == i&lt;/code&gt;). Each such element represents the root of a distinct group. This approach is slightly less efficient if &lt;code&gt;N&lt;/code&gt; is very large, but conceptually equivalent. Using the &lt;code&gt;num_groups&lt;/code&gt; counter within the &lt;code&gt;union&lt;/code&gt; method is generally preferred for its simplicity and directness.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="implementing-the-solution-python"&gt;Implementing the Solution: Python&lt;/h2&gt;
&lt;p&gt;Let's put these steps into action with Python code. We'll define a &lt;code&gt;DSU&lt;/code&gt; class and a helper function for similarity checking.&lt;/p&gt;
&lt;h3 id="helper-function-aresimilars1-s2"&gt;Helper Function: &lt;code&gt;areSimilar(s1, s2)&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;This function checks if two strings are similar according to the problem's definition.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;areSimilar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;    Checks if two strings s1 and s2 are similar.&lt;/span&gt;
&lt;span class="sd"&gt;    Similar means they can be made identical by swapping exactly two characters.&lt;/span&gt;
&lt;span class="sd"&gt;    This also covers identical strings (0 differences).&lt;/span&gt;
&lt;span class="sd"&gt;    &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="n"&gt;diff&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;)):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
            &lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Case 1: Strings are identical&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;

    &lt;span class="c1"&gt;# Case 2: Strings differ by exactly two characters&lt;/span&gt;
    &lt;span class="c1"&gt;# Check if swapping these two characters makes them identical&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idx2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="c1"&gt;# Case 3: Strings differ by 1 or more than 2 characters&lt;/span&gt;
    &lt;span class="c1"&gt;# Not similar&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="dsu-class-in-python"&gt;DSU Class in Python&lt;/h3&gt;
&lt;p&gt;We'll implement a &lt;code&gt;DSU&lt;/code&gt; class with &lt;code&gt;find&lt;/code&gt;, &lt;code&gt;union&lt;/code&gt;, and a &lt;code&gt;count&lt;/code&gt; of groups.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Initializes the DSU structure for n elements.&lt;/span&gt;
&lt;span class="sd"&gt;        Each element is initially its own parent and forms a group of size 1.&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;  &lt;span class="c1"&gt;# For union by size optimization&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;num_groups&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;  &lt;span class="c1"&gt;# Initialize with n groups&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Finds the representative (root) of the set containing element i.&lt;/span&gt;
&lt;span class="sd"&gt;        Applies path compression for optimization.&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="c1"&gt;# Path compression&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;union&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Unites the sets containing elements i and j.&lt;/span&gt;
&lt;span class="sd"&gt;        Applies union by size optimization.&lt;/span&gt;
&lt;span class="sd"&gt;        Returns True if a merge happened, False otherwise.&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="n"&gt;root_i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;root_j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;root_i&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="c1"&gt;# Union by size: attach smaller tree to root of larger tree&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;root_j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;root_i&lt;/span&gt;  &lt;span class="c1"&gt;# Swap to ensure root_i is larger/equal&lt;/span&gt;

            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;root_i&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;num_groups&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Decrement group count as two groups merged&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="main-solution-logic-for-839-similar-string-groups"&gt;Main Solution Logic for 839 Similar String Groups&lt;/h3&gt;
&lt;p&gt;Now, combine the &lt;code&gt;DSU&lt;/code&gt; and &lt;code&gt;areSimilar&lt;/code&gt; function into the main &lt;code&gt;numSimilarGroups&lt;/code&gt; function.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;numSimilarGroups&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Initialize DSU for n strings&lt;/span&gt;
        &lt;span class="n"&gt;dsu&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Iterate through all unique pairs of strings&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="c1"&gt;# Check if strings strs[i] and strs[j] are similar&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;areSimilar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]):&lt;/span&gt;
                    &lt;span class="c1"&gt;# If similar, unite their sets in DSU&lt;/span&gt;
                    &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;union&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# The number of groups is stored in dsu.num_groups&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;num_groups&lt;/span&gt;

&lt;span class="c1"&gt;# Helper function defined outside the Solution class or nested inside for competitive programming platforms&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;areSimilar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;diff&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;)):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
            &lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idx2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="python-time-and-space-complexity-analysis"&gt;Python Time and Space Complexity Analysis&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Let &lt;code&gt;N&lt;/code&gt; be the number of strings and &lt;code&gt;L&lt;/code&gt; be the length of each string.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;areSimilar&lt;/code&gt; function:&lt;/strong&gt; Takes &lt;code&gt;O(L)&lt;/code&gt; time to compare two strings.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Main loops:&lt;/strong&gt; We iterate through &lt;code&gt;N * (N - 1) / 2&lt;/code&gt;, which is &lt;code&gt;O(N^2)&lt;/code&gt; pairs of strings.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DSU operations:&lt;/strong&gt; Each &lt;code&gt;find&lt;/code&gt; and &lt;code&gt;union&lt;/code&gt; operation, with path compression and union by size, takes nearly constant time, amortized &lt;code&gt;O(alpha(N))&lt;/code&gt;, where &lt;code&gt;alpha&lt;/code&gt; is the inverse Ackermann function.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Total Time Complexity:&lt;/strong&gt; &lt;code&gt;O(N^2 * L + N * alpha(N))&lt;/code&gt; which simplifies to &lt;code&gt;O(N^2 * L)&lt;/code&gt; because &lt;code&gt;alpha(N)&lt;/code&gt; is practically a constant, and &lt;code&gt;L&lt;/code&gt; is typically much larger than &lt;code&gt;alpha(N)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;DSU&lt;/code&gt; class:&lt;/strong&gt; Stores &lt;code&gt;parent&lt;/code&gt; and &lt;code&gt;size&lt;/code&gt; arrays of size &lt;code&gt;N&lt;/code&gt;. So, &lt;code&gt;O(N)&lt;/code&gt; space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;areSimilar&lt;/code&gt; function:&lt;/strong&gt; &lt;code&gt;diff&lt;/code&gt; list stores at most &lt;code&gt;L&lt;/code&gt; indices. So, &lt;code&gt;O(L)&lt;/code&gt; space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Total Space Complexity:&lt;/strong&gt; &lt;code&gt;O(N + L)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="implementing-the-solution-c"&gt;Implementing the Solution: C++&lt;/h2&gt;
&lt;p&gt;Next, let's look at the C++ implementation for the 839 Similar String Groups leetcode question. We'll use a class for DSU and a standalone helper function.&lt;/p&gt;
&lt;h3 id="helper-function-aresimilarstring-s1-string-s2"&gt;Helper Function: &lt;code&gt;areSimilar(string&amp;amp; s1, string&amp;amp; s2)&lt;/code&gt;&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;string&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;numeric&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // For iota&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;algorithm&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // For std::swap&lt;/span&gt;

&lt;span class="c1"&gt;// Helper function to check if two strings are similar&lt;/span&gt;
&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;areSimilar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Case 1: Strings are identical&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Case 2: Strings differ by exactly two characters&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Check if swapping these two characters makes them identical&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Case 3: Strings differ by 1 or more than 2 characters&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;false&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;h3 id="dsu-class-in-c"&gt;DSU Class in C++&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;DSU&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sz&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// For union by size optimization&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;num_groups&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;iota&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;begin&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Initialize parent[i] = i&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;sz&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;assign&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Initialize size of each group to 1&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;num_groups&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Initially n groups&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Path compression&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;unite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Union by size: attach smaller tree to root of larger tree&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sz&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sz&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;swap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Ensure root_i is the root of the larger/equal sized tree&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;sz&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;sz&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;num_groups&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Decrement group count&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="main-solution-logic-for-839-similar-string-groups_1"&gt;Main Solution Logic for 839 Similar String Groups&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Helper function (can be defined as a private member or a global function)&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;areSimilar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numSimilarGroups&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Initialize DSU for n strings&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Iterate through all unique pairs of strings&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// Check if strings strs[i] and strs[j] are similar&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;areSimilar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// If similar, unite their sets in DSU&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;unite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// The number of groups is stored in dsu.num_groups&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;num_groups&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="c-time-and-space-complexity-analysis"&gt;C++ Time and Space Complexity Analysis&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Let &lt;code&gt;N&lt;/code&gt; be the number of strings and &lt;code&gt;L&lt;/code&gt; be the length of each string.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;areSimilar&lt;/code&gt; function:&lt;/strong&gt; Takes &lt;code&gt;O(L)&lt;/code&gt; time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Main loops:&lt;/strong&gt; &lt;code&gt;O(N^2)&lt;/code&gt; pairs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DSU operations:&lt;/strong&gt; Amortized &lt;code&gt;O(alpha(N))&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Total Time Complexity:&lt;/strong&gt; &lt;code&gt;O(N^2 * L)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;DSU&lt;/code&gt; class:&lt;/strong&gt; &lt;code&gt;parent&lt;/code&gt; and &lt;code&gt;sz&lt;/code&gt; vectors of size &lt;code&gt;N&lt;/code&gt;. So, &lt;code&gt;O(N)&lt;/code&gt; space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;areSimilar&lt;/code&gt; function:&lt;/strong&gt; &lt;code&gt;diff&lt;/code&gt; vector stores at most &lt;code&gt;L&lt;/code&gt; indices. So, &lt;code&gt;O(L)&lt;/code&gt; space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Total Space Complexity:&lt;/strong&gt; &lt;code&gt;O(N + L)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="implementing-the-solution-java"&gt;Implementing the Solution: Java&lt;/h2&gt;
&lt;p&gt;Finally, let's implement the solution for the 839 Similar String Groups leetcode question in Java. We'll use an inner class for &lt;code&gt;DSU&lt;/code&gt; within the &lt;code&gt;Solution&lt;/code&gt; class.&lt;/p&gt;
&lt;h3 id="helper-function-aresimilarstring-s1-string-s2_1"&gt;Helper Function: &lt;code&gt;areSimilar(String s1, String s2)&lt;/code&gt;&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.ArrayList&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.List&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Helper function to check if two strings are similar&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;areSimilar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Case 1: Strings are identical&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isEmpty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Case 2: Strings differ by exactly two characters&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Check if swapping these two characters makes them identical&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Case 3: Strings differ by 1 or more than 2 characters&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// ... DSU class and numSimilarGroups method will go here&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="dsu-class-in-java"&gt;DSU Class in Java&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.ArrayList&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.List&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.Arrays&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// For Arrays.fill and Arrays.setAll&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Inner DSU class&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DSU&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// For union by size optimization&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numGroups&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Initialize parent[i] = i&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;fill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Initialize size of each group to 1&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;numGroups&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Initially n groups&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Path compression&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;unionSets&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// Union by size: attach smaller tree to root of larger tree&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Swap to ensure rootI is the root of the larger/equal sized tree&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;numGroups&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Decrement group count&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// ... areSimilar method and numSimilarGroups method will go here&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="main-solution-logic-for-839-similar-string-groups_2"&gt;Main Solution Logic for 839 Similar String Groups&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.ArrayList&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.List&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.Arrays&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Helper function to check if two strings are similar&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;areSimilar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isEmpty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;diff&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Inner DSU class&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DSU&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numGroups&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;fill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;numGroups&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;unionSets&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootI&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;rootJ&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;numGroups&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;numSimilarGroups&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Initialize DSU for n strings&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Iterate through all unique pairs of strings&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// Check if strings strs[i] and strs[j] are similar&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;areSimilar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// If similar, unite their sets in DSU&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;unionSets&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// The number of groups is stored in dsu.numGroups&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;numGroups&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="java-time-and-space-complexity-analysis"&gt;Java Time and Space Complexity Analysis&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Let &lt;code&gt;N&lt;/code&gt; be the number of strings and &lt;code&gt;L&lt;/code&gt; be the length of each string.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;areSimilar&lt;/code&gt; function:&lt;/strong&gt; Takes &lt;code&gt;O(L)&lt;/code&gt; time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Main loops:&lt;/strong&gt; &lt;code&gt;O(N^2)&lt;/code&gt; pairs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DSU operations:&lt;/strong&gt; Amortized &lt;code&gt;O(alpha(N))&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Total Time Complexity:&lt;/strong&gt; &lt;code&gt;O(N^2 * L)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;DSU&lt;/code&gt; class:&lt;/strong&gt; &lt;code&gt;parent&lt;/code&gt; and &lt;code&gt;size&lt;/code&gt; arrays of size &lt;code&gt;N&lt;/code&gt;. So, &lt;code&gt;O(N)&lt;/code&gt; space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;areSimilar&lt;/code&gt; function:&lt;/strong&gt; &lt;code&gt;diff&lt;/code&gt; list stores at most &lt;code&gt;L&lt;/code&gt; indices. So, &lt;code&gt;O(L)&lt;/code&gt; space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Total Space Complexity:&lt;/strong&gt; &lt;code&gt;O(N + L)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="common-pitfalls-and-considerations"&gt;Common Pitfalls and Considerations&lt;/h2&gt;
&lt;p&gt;While the DSU approach is straightforward, a few common mistakes can lead to incorrect solutions or Time Limit Exceeded (TLE).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Incorrect &lt;code&gt;areSimilar&lt;/code&gt; Logic:&lt;/strong&gt; The most crucial part is correctly implementing the similarity check. Many candidates might misinterpret "swap exactly two characters." Forgetting to handle identical strings (zero differences) or mistakenly allowing strings with more than two differences will lead to errors. Ensure the check for &lt;code&gt;s1[idx1] == s2[idx2] &amp;amp;&amp;amp; s1[idx2] == s2[idx1]&lt;/code&gt; is correct for the two-difference case.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DSU Implementation Errors:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Missing Path Compression:&lt;/strong&gt; Without path compression in the &lt;code&gt;find&lt;/code&gt; operation, the DSU trees can become very deep, degrading &lt;code&gt;find&lt;/code&gt; and &lt;code&gt;union&lt;/code&gt; operations to &lt;code&gt;O(N)&lt;/code&gt; in the worst case. This would increase overall complexity significantly, often resulting in TLE for larger inputs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Missing Union by Rank/Size:&lt;/strong&gt; Similar to path compression, not using union by rank or size can lead to skewed trees, also causing &lt;code&gt;O(N)&lt;/code&gt; worst-case performance for DSU operations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Incorrect &lt;code&gt;num_groups&lt;/code&gt; Decrement:&lt;/strong&gt; If you're using a &lt;code&gt;num_groups&lt;/code&gt; counter, ensure it's decremented only when &lt;code&gt;union&lt;/code&gt; successfully merges two &lt;em&gt;different&lt;/em&gt; sets. If &lt;code&gt;root_i == root_j&lt;/code&gt;, no merge happens, and the count should not change.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Time Limit Exceeded (TLE) - &lt;code&gt;O(N^2 * L)&lt;/code&gt;:&lt;/strong&gt; This complexity is inherent to the problem's constraints (comparing all pairs).&lt;ul&gt;
&lt;li&gt;For &lt;code&gt;N&lt;/code&gt; up to 100, &lt;code&gt;N^2&lt;/code&gt; is &lt;code&gt;100^2 = 10,000&lt;/code&gt;. If &lt;code&gt;L&lt;/code&gt; is up to 60, &lt;code&gt;N^2 * L&lt;/code&gt; is &lt;code&gt;10,000 * 60 = 600,000&lt;/code&gt;, which is perfectly acceptable.&lt;/li&gt;
&lt;li&gt;However, if &lt;code&gt;N&lt;/code&gt; is larger (e.g., 2000), &lt;code&gt;N^2&lt;/code&gt; is &lt;code&gt;4 * 10^6&lt;/code&gt;. With &lt;code&gt;L=60&lt;/code&gt;, this becomes &lt;code&gt;2.4 * 10^8&lt;/code&gt;, which might be too slow for a typical 1-second time limit. For this specific problem (N up to 100), &lt;code&gt;O(N^2 * L)&lt;/code&gt; is expected. Be aware of the constraints for future problems.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;String Hashing Optimization:&lt;/strong&gt; For problems with larger &lt;code&gt;N&lt;/code&gt; but smaller &lt;code&gt;L&lt;/code&gt;, or if many duplicate strings are expected, you &lt;em&gt;might&lt;/em&gt; consider string hashing to group identical strings initially and then map them to integer IDs to reduce the &lt;code&gt;N&lt;/code&gt; for DSU. However, for LeetCode 839, the provided constraints (&lt;code&gt;N&lt;/code&gt; up to 100) mean the &lt;code&gt;O(N^2 * L)&lt;/code&gt; approach is perfectly fine and preferred for its simplicity.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="further-optimizations-and-advanced-topics"&gt;Further Optimizations and Advanced Topics&lt;/h2&gt;
&lt;p&gt;While the &lt;code&gt;O(N^2 * L)&lt;/code&gt; DSU solution is optimal for the given constraints of LeetCode 839, it's worth briefly touching on scenarios where further optimization might be considered.&lt;/p&gt;
&lt;h3 id="handling-larger-n-number-of-strings"&gt;Handling Larger N (Number of Strings)&lt;/h3&gt;
&lt;p&gt;If &lt;code&gt;N&lt;/code&gt; were significantly larger (e.g., &lt;code&gt;10^5&lt;/code&gt;) but &lt;code&gt;L&lt;/code&gt; (string length) remained relatively small, the &lt;code&gt;O(N^2)&lt;/code&gt; string comparisons would be too slow. In such advanced cases, the approach would shift towards using &lt;strong&gt;hashing&lt;/strong&gt; and &lt;strong&gt;graph-traversal algorithms&lt;/strong&gt; instead of direct DSU on all pairs:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Generate Permutations/Neighbors:&lt;/strong&gt; For each string &lt;code&gt;s&lt;/code&gt;, generate all possible "similar" strings by trying to swap every pair of characters. This generates &lt;code&gt;O(L^2)&lt;/code&gt; potential neighbors.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hashing and Adjacency List:&lt;/strong&gt; Store all input strings in a hash set (or &lt;code&gt;unordered_map&lt;/code&gt; in C++, &lt;code&gt;HashSet&lt;/code&gt; in Java) for &lt;code&gt;O(1)&lt;/code&gt; average-time lookups. For each input string &lt;code&gt;s&lt;/code&gt;, iterate through its &lt;code&gt;O(L^2)&lt;/code&gt; generated similar strings &lt;code&gt;s'&lt;/code&gt;. If &lt;code&gt;s'&lt;/code&gt; exists in the hash set, &lt;code&gt;s&lt;/code&gt; and &lt;code&gt;s'&lt;/code&gt; are similar. Build an adjacency list &lt;code&gt;graph[s]&lt;/code&gt; containing &lt;code&gt;s'&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graph Traversal (BFS/DFS):&lt;/strong&gt; Once the graph (or a partial graph for similar strings) is built, perform a graph traversal (BFS or DFS) to find connected components. Count the number of times you start a new traversal from an unvisited node. This would typically bring the complexity closer to &lt;code&gt;O(N * L^2 * alpha(N))&lt;/code&gt; or &lt;code&gt;O(N * L^2 + N + E)&lt;/code&gt; where E is number of edges (which could be &lt;code&gt;N * L^2&lt;/code&gt; in worst case).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;However, this &lt;code&gt;O(N * L^2)&lt;/code&gt; approach only works if &lt;code&gt;L^2&lt;/code&gt; is small enough. For LeetCode 839, &lt;code&gt;L&lt;/code&gt; is up to 60, so &lt;code&gt;L^2&lt;/code&gt; is &lt;code&gt;3600&lt;/code&gt;. &lt;code&gt;N * L^2&lt;/code&gt; would be &lt;code&gt;100 * 3600 = 3.6 * 10^5&lt;/code&gt;, which is faster than &lt;code&gt;N^2 * L = 100^2 * 60 = 6 * 10^5&lt;/code&gt; in this specific scenario, but the constant factors and overhead of generating permutations can make it slower in practice for the given constraints. The &lt;code&gt;N^2 * L&lt;/code&gt; approach is simpler to implement and often performs better for &lt;code&gt;N&lt;/code&gt; up to around 100-200.&lt;/p&gt;
&lt;h3 id="trie-based-optimization"&gt;Trie-based Optimization&lt;/h3&gt;
&lt;p&gt;Another highly complex optimization for very specific string similarity definitions (like Hamming distance 1 or 2) can involve Tries. If you need to find all strings "similar" to a given string very quickly across a large dictionary of strings, a Trie could be used to efficiently search for neighbors. This is generally overkill for a "swap two characters" similarity and the given constraints.&lt;/p&gt;
&lt;p&gt;For the purpose of the 839 Similar String Groups leetcode question, sticking with the &lt;code&gt;O(N^2 * L)&lt;/code&gt; DSU approach is the standard and most effective solution. The primary takeaway should be the correct application of DSU and the precise definition of "similar strings."&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The 839 Similar String Groups LeetCode problem is an excellent exercise in applying the Disjoint Set Union (DSU) data structure to solve connectivity problems. By modeling the strings as nodes in a graph and defining similarity as an edge, we effectively transform the problem into finding the number of connected components. The efficiency of DSU, particularly with path compression and union by size optimizations, makes it the ideal tool for handling the transitive nature of string similarity.&lt;/p&gt;
&lt;p&gt;This tutorial has guided you through a comprehensive understanding of the problem, the theoretical underpinnings of DSU, and detailed implementations in Python, C++, and Java. Mastering these concepts and their practical application is crucial for competitive programming and algorithm design, much like understanding &lt;a href="/dijkstra-algorithm-python-cpp-java-tutorial/"&gt;Dijkstra's Algorithm&lt;/a&gt; or other fundamental graph traversals. Continue to practice similar problems to solidify your understanding of DSU and its versatility in solving complex grouping and connectivity challenges.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What defines "similar" strings in LeetCode 839?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Two strings are similar if they are identical (zero differences), or if they can be made identical by swapping exactly two characters. If they differ by only one character or by more than two characters, they are not considered similar.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Why is Disjoint Set Union (DSU) suitable for this problem?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: DSU is ideal because string similarity is transitive: if A is similar to B and B to C, then A, B, and C are all in the same group. DSU efficiently manages these equivalence classes, allowing quick merging of related groups and counting the final distinct sets.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the time complexity of the solution?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The overall time complexity of this solution is O(N^2 * L), where N is the number of strings in the input array and L is the length of each string. This accounts for iterating through all N^2 pairs and performing an O(L) similarity check for each.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/similar-string-groups/"&gt;LeetCode Problem 839: Similar String Groups&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://cp-algorithms.com/data_structures/disjoint_set_union.html"&gt;Disjoint Set Union (Union-Find) Data Structure Explained&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/"&gt;Introduction to Graph Theory&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Java"/><category term="C Plus Plus"/><category term="Coding Interview"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/839-similar-string-groups-leetcode-python-cpp-java-tutorial.webp" width="1200"/><media:title type="plain">839 Similar String Groups LeetCode: Python, C++, Java Solutions</media:title><media:description type="plain">Solve LeetCode 839 Similar String Groups effectively. This tutorial provides comprehensive solutions in Python, C++, and Java using Disjoint Set Union (DSU) ...</media:description></entry><entry><title>2092. Find All People With Secret: LeetCode Tutorial in C++, Python, Java</title><link href="https://analyticsdrive.tech/find-all-people-with-secret-leetcode-2092-tutorial/" rel="alternate"/><published>2026-03-12T15:25:00+05:30</published><updated>2026-03-12T15:25:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-12:/find-all-people-with-secret-leetcode-2092-tutorial/</id><summary type="html">&lt;p&gt;Master LeetCode 2092. Find All People With Secret using C++, Python, and Java. This tutorial guides you through an efficient solution for this challenging gr...&lt;/p&gt;</summary><content type="html">&lt;p&gt;This tutorial provides a comprehensive guide to solving the 2092. Find All People With Secret leetcode question in c++, python,java, offering efficient strategies and complete code implementations for competitive programming enthusiasts. Understanding how secrets propagate among individuals is a fascinating problem that often appears in competitive programming challenges. One such intriguing scenario is presented in LeetCode problem 2092, aptly titled "Find All People With Secret". By the end of this tutorial, you will have a solid understanding of the problem's nuances, the critical algorithms involved, and how to implement a robust solution to find all people with secret knowledge, starting from an initial set of secret holders. We'll explore the core concepts and techniques required to tackle this problem effectively.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#understanding-the-find-all-people-with-secret-problem"&gt;Understanding the "Find All People With Secret" Problem&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#problem-description"&gt;Problem Description&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-challenges"&gt;Core Challenges&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-solving-leetcode-2092"&gt;Prerequisites for Solving LeetCode 2092&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#basic-graph-theory"&gt;Basic Graph Theory&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#disjoint-set-union-dsu"&gt;Disjoint Set Union (DSU)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#sorting-and-time-complexity-analysis"&gt;Sorting and Time Complexity Analysis&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-by-step-solution-finding-all-people-with-secret"&gt;Step-by-Step Solution: Finding All People With Secret&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-1-analyze-the-problem-constraints-and-structure"&gt;Step 1: Analyze the Problem Constraints and Structure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-2-sort-meetings-by-time"&gt;Step 2: Sort Meetings by Time&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-3-initialize-disjoint-set-union-dsu-structure"&gt;Step 3: Initialize Disjoint Set Union (DSU) Structure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-4-process-meetings-in-groups"&gt;Step 4: Process Meetings in Groups&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-5-perform-union-operations-for-each-group"&gt;Step 5: Perform Union Operations for Each Group&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-6-identify-and-reset-non-secret-holders"&gt;Step 6: Identify and Reset Non-Secret Holders&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-7-collect-all-secret-holders"&gt;Step 7: Collect All Secret Holders&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#code-implementation-for-find-all-people-with-secret"&gt;Code Implementation for "Find All People With Secret"&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#python-solution"&gt;Python Solution&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#c-solution"&gt;C++ Solution&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#java-solution"&gt;Java Solution&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-analysis-for-2092-find-all-people-with-secret-leetcode-solution"&gt;Time and Space Complexity Analysis for 2092. Find All People With Secret LeetCode Solution&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-best-practices-for-2092-find-all-people-with-secret-leetcode-question"&gt;Common Mistakes and Best Practices for 2092. Find All People With Secret LeetCode Question&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#incorrect-dsu-initialization"&gt;Incorrect DSU Initialization&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#not-sorting-meetings-by-time"&gt;Not Sorting Meetings by Time&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#missing-the-reset-step"&gt;Missing the Reset Step&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#inefficient-grouping-of-meetings"&gt;Inefficient Grouping of Meetings&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#off-by-one-errors-or-indexing-issues"&gt;Off-by-One Errors or Indexing Issues&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="understanding-the-find-all-people-with-secret-problem"&gt;Understanding the "Find All People With Secret" Problem&lt;/h2&gt;
&lt;p&gt;LeetCode 2092, "Find All People With Secret," is a captivating problem that blends graph theory, time-based processing, and a clever application of the Disjoint Set Union (DSU) data structure. The essence of the problem lies in tracking the flow of confidential information through a series of meetings.&lt;/p&gt;
&lt;h3 id="problem-description"&gt;Problem Description&lt;/h3&gt;
&lt;p&gt;You are given &lt;code&gt;n&lt;/code&gt; people, labeled from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n - 1&lt;/code&gt;. Initially, person &lt;code&gt;0&lt;/code&gt; has a secret, and there's another person, &lt;code&gt;firstPerson&lt;/code&gt;, who also knows the secret. All other people initially do not know the secret.&lt;/p&gt;
&lt;p&gt;You are also given a list of &lt;code&gt;meetings&lt;/code&gt;, where &lt;code&gt;meetings[i] = [x_i, y_i, time_i]&lt;/code&gt;. This indicates that person &lt;code&gt;x_i&lt;/code&gt; and person &lt;code&gt;y_i&lt;/code&gt; meet at &lt;code&gt;time_i&lt;/code&gt;. A meeting can only share a secret if &lt;em&gt;both&lt;/em&gt; participants already know the secret &lt;em&gt;at or before&lt;/em&gt; the &lt;code&gt;time_i&lt;/code&gt; of the meeting. If one person knows the secret and meets another person who doesn't, the secret is shared, and the second person now also knows it. This propagation continues: if person A knows the secret and meets person B, and person B meets person C, then C eventually learns the secret if all meetings happen in a sequence where the secret can propagate.&lt;/p&gt;
&lt;p&gt;The critical constraint is that secrets are only shared &lt;em&gt;forward&lt;/em&gt; in time. If someone learns a secret at time &lt;code&gt;t&lt;/code&gt;, they can only share it in meetings occurring at time &lt;code&gt;t&lt;/code&gt; or later. They cannot retroactively share it in a meeting that occurred before &lt;code&gt;t&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Your task is to return a list of all the people who eventually know the secret.&lt;/p&gt;
&lt;p&gt;Let's consider an example: &lt;code&gt;n = 6&lt;/code&gt;, &lt;code&gt;meetings = [[0,2,1],[1,3,1],[4,5,2]]&lt;/code&gt;, &lt;code&gt;firstPerson = 1&lt;/code&gt;.
Initially: Person 0 and Person 1 know the secret.
Meetings at time &lt;code&gt;t=1&lt;/code&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;code&gt;[0,2,1]&lt;/code&gt;: Person 0 knows the secret. Person 2 does not. After the meeting, Person 2 learns the secret.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;[1,3,1]&lt;/code&gt;: Person 1 knows the secret. Person 3 does not. After the meeting, Person 3 learns the secret.
    Now, at the end of &lt;code&gt;t=1&lt;/code&gt;, people 0, 1, 2, 3 know the secret.
    Meetings at time &lt;code&gt;t=2&lt;/code&gt;:&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;[4,5,2]&lt;/code&gt;: Person 4 does not know the secret, and Person 5 does not know the secret. No secret is shared.
    Final secret holders: 0, 1, 2, 3.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="core-challenges"&gt;Core Challenges&lt;/h3&gt;
&lt;p&gt;The complexity of the 2092. Find All People With Secret leetcode question in c++, python,java stems from several interconnected factors:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Time-Dependent Propagation:&lt;/strong&gt; Secrets are shared sequentially based on meeting times. This means the order of processing meetings is crucial. Meetings must be considered in chronological order.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Transitive Sharing:&lt;/strong&gt; If A meets B, and B meets C, the secret can pass from A to C (via B), provided these meetings occur at times that allow for propagation. This suggests a graph-like structure where connections form and secrets spread.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Conditional Secret Knowledge:&lt;/strong&gt; A person only shares a secret if they &lt;em&gt;already&lt;/em&gt; know it at the time of the meeting. If person X meets person Y at time &lt;code&gt;t&lt;/code&gt;, and X knows the secret but Y does not, Y learns it. If neither knows it, no secret is shared. This isn't a simple graph traversal where all connected components automatically share.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resetting Knowledge (Implicitly):&lt;/strong&gt; If a group of people meets at a certain time &lt;code&gt;t&lt;/code&gt;, and after all meetings at time &lt;code&gt;t&lt;/code&gt; are considered, some of these people are &lt;em&gt;not&lt;/em&gt; connected to someone who &lt;em&gt;definitively&lt;/em&gt; had the secret at time &lt;code&gt;t&lt;/code&gt;, then they do &lt;em&gt;not&lt;/em&gt; gain the secret. Their potential connections formed &lt;em&gt;only&lt;/em&gt; within that time group must be "reset" for future time steps if they didn't get the secret. This is arguably the trickiest part.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These challenges point towards an algorithm that can efficiently model dynamic connections, track group membership, and handle time-ordered conditional updates.&lt;/p&gt;
&lt;h2 id="prerequisites-for-solving-leetcode-2092"&gt;Prerequisites for Solving LeetCode 2092&lt;/h2&gt;
&lt;p&gt;To effectively tackle the 2092. Find All People With Secret leetcode question in c++, python,java, a solid grasp of certain fundamental data structures and algorithms is essential. This problem serves as an excellent test of your understanding of these concepts.&lt;/p&gt;
&lt;h3 id="basic-graph-theory"&gt;Basic Graph Theory&lt;/h3&gt;
&lt;p&gt;The problem inherently models relationships between people, which can be visualized as a graph.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Nodes (Vertices):&lt;/strong&gt; Each person &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt; represents a node in the graph.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edges:&lt;/strong&gt; A meeting &lt;code&gt;[x, y, time]&lt;/code&gt; can be thought of as a potential edge between &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; that exists at &lt;code&gt;time&lt;/code&gt;.
Understanding how these nodes and edges form connections is crucial. While we won't build an explicit adjacency list for the entire graph over all times, the concept of interconnected components is central. For another excellent example of graph traversal, consider exploring a &lt;a href="/number-of-islands-graph-traversal-tutorial/"&gt;deep dive into graph traversal algorithms like those used in the Number Of Islands problem&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="disjoint-set-union-dsu"&gt;Disjoint Set Union (DSU)&lt;/h3&gt;
&lt;p&gt;The Disjoint Set Union (also known as Union-Find) data structure is indispensable for solving this problem efficiently. DSU is optimized for managing a collection of disjoint sets, performing two primary operations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;find(i)&lt;/code&gt;:&lt;/strong&gt; Determines the representative (or root) of the set to which element &lt;code&gt;i&lt;/code&gt; belongs. This effectively tells you which set &lt;code&gt;i&lt;/code&gt; is a part of.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;union(i, j)&lt;/code&gt;:&lt;/strong&gt; Merges the sets containing elements &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;j&lt;/code&gt; into a single set.
DSU is perfect for problems where you need to track connected components or group elements. Key optimizations for DSU include path compression (during &lt;code&gt;find&lt;/code&gt;) and union by rank or size (during &lt;code&gt;union&lt;/code&gt;), which bring its amortized time complexity for both operations very close to O(1). This makes it particularly useful for challenges similar to &lt;a href="/leetcode-1976-number-of-ways-arrive-destination-tutorial/"&gt;Leetcode 1976: Number of Ways to Arrive at Destination Explained&lt;/a&gt; or other path-finding scenarios.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the context of this problem, DSU will help us:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Identify groups of people who are connected and thus can potentially share a secret at a specific time.&lt;/li&gt;
&lt;li&gt;Quickly check if a person is connected to the initial secret holders (person &lt;code&gt;0&lt;/code&gt; or &lt;code&gt;firstPerson&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="sorting-and-time-complexity-analysis"&gt;Sorting and Time Complexity Analysis&lt;/h3&gt;
&lt;p&gt;The time-dependent nature of the secret propagation necessitates processing meetings in chronological order. Therefore, sorting the &lt;code&gt;meetings&lt;/code&gt; array by &lt;code&gt;time_i&lt;/code&gt; is a fundamental first step.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Sorting Algorithms:&lt;/strong&gt; Familiarity with algorithms like Merge Sort or Quick Sort (which &lt;code&gt;std::sort&lt;/code&gt; in C++, &lt;code&gt;sorted()&lt;/code&gt; in Python, or &lt;code&gt;Collections.sort()&lt;/code&gt; in Java typically use) is important.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; Understanding how to analyze the time complexity of your solution (e.g., O(N log N) for sorting, amortized O(alpha(N)) for DSU operations where alpha is the inverse Ackermann function, which is practically constant) is crucial for building an efficient algorithm that passes within typical time limits. For other important graph algorithms that rely on efficient traversal and pathfinding, you can review tutorials such as &lt;a href="/dijkstra-algorithm-python-cpp-java-tutorial/"&gt;Dijkstra Algorithm in Python, C++, Java&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="step-by-step-solution-finding-all-people-with-secret"&gt;Step-by-Step Solution: Finding All People With Secret&lt;/h2&gt;
&lt;p&gt;The optimal approach to the "Find All People With Secret" problem involves a combination of sorting, the Disjoint Set Union (DSU) data structure, and careful time-based processing. Let's break down the solution into manageable steps.&lt;/p&gt;
&lt;h3 id="step-1-analyze-the-problem-constraints-and-structure"&gt;Step 1: Analyze the Problem Constraints and Structure&lt;/h3&gt;
&lt;p&gt;Before diving into implementation, it's vital to understand the scale of the problem.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;n&lt;/code&gt; (number of people) can be up to &lt;code&gt;10^5&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;meetings&lt;/code&gt; can be up to &lt;code&gt;10^5&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;time_i&lt;/code&gt; can be up to &lt;code&gt;10^5&lt;/code&gt;.
These constraints suggest that a solution with complexity around O((N + M) * log M) or O((N + M) * alpha(N)) (where M is number of meetings) will be required. Direct graph traversal on a potentially dense graph for each time step would be too slow. The DSU approach, with its near-constant time operations, fits well within these bounds.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-2-sort-meetings-by-time"&gt;Step 2: Sort Meetings by Time&lt;/h3&gt;
&lt;p&gt;The core principle of secret propagation is its adherence to a chronological order. A secret cannot be shared in a past meeting. Therefore, the very first step is to sort all &lt;code&gt;meetings&lt;/code&gt; based on their &lt;code&gt;time_i&lt;/code&gt; in ascending order. If two meetings occur at the same time, their relative order doesn't matter for correctness, but processing them together is key.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Python&lt;/span&gt;
&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;// C++&lt;/span&gt;
&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;begin&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[](&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&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;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;// Java&lt;/span&gt;
&lt;span class="n"&gt;Collections&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;compare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="step-3-initialize-disjoint-set-union-dsu-structure"&gt;Step 3: Initialize Disjoint Set Union (DSU) Structure&lt;/h3&gt;
&lt;p&gt;We need a DSU structure to keep track of connected components. Each person will initially be in their own set.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;parent&lt;/code&gt; array: &lt;code&gt;parent[i]&lt;/code&gt; stores the parent of person &lt;code&gt;i&lt;/code&gt;. If &lt;code&gt;parent[i] == i&lt;/code&gt;, then &lt;code&gt;i&lt;/code&gt; is the root of its set.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;rank&lt;/code&gt; or &lt;code&gt;size&lt;/code&gt; array: Used for optimization during union (union by rank/size) to keep the tree shallow. &lt;code&gt;rank[i]&lt;/code&gt; could store the height of the tree rooted at &lt;code&gt;i&lt;/code&gt;, or &lt;code&gt;size[i]&lt;/code&gt; could store the number of nodes in the tree rooted at &lt;code&gt;i&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Initialize the DSU structure:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Set &lt;code&gt;parent[i] = i&lt;/code&gt; for all &lt;code&gt;i&lt;/code&gt; from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;rank[i] = 0&lt;/code&gt; (or &lt;code&gt;size[i] = 1&lt;/code&gt;) for all &lt;code&gt;i&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Crucially, person &lt;code&gt;0&lt;/code&gt; and &lt;code&gt;firstPerson&lt;/code&gt; initially know the secret. They should be connected in our DSU from the start. So, perform &lt;code&gt;union(0, firstPerson)&lt;/code&gt; after initializing the DSU for everyone.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Python DSU class structure&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;union&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;root_i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;root_j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;root_i&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;root_j&lt;/span&gt;
            &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;root_i&lt;/span&gt;
            &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;root_i&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;

&lt;span class="c1"&gt;# Initialization&lt;/span&gt;
&lt;span class="n"&gt;dsu&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;union&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;firstPerson&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="step-4-process-meetings-in-groups"&gt;Step 4: Process Meetings in Groups&lt;/h3&gt;
&lt;p&gt;Iterate through the sorted meetings. Since multiple meetings can occur at the same time, it's more efficient to process all meetings occurring at time &lt;code&gt;t&lt;/code&gt; together. This is crucial for correctly applying the DSU logic.
We can use a pointer to iterate through the sorted &lt;code&gt;meetings&lt;/code&gt; list, processing meetings that share the same timestamp in a batch.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Python structure for grouping&lt;/span&gt;
&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;
    &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;temp_people&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# To store all people involved in meetings at current_time&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="n"&gt;temp_people&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;temp_people&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="c1"&gt;# ... (union operations will go here)&lt;/span&gt;
        &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="c1"&gt;# ... (reset logic will go here)&lt;/span&gt;
    &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="step-5-perform-union-operations-for-each-group"&gt;Step 5: Perform Union Operations for Each Group&lt;/h3&gt;
&lt;p&gt;For each group of meetings occurring at the &lt;code&gt;current_time&lt;/code&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Identify all people involved in these meetings. Store them temporarily (e.g., in a &lt;code&gt;temp_people&lt;/code&gt; set or list).&lt;/li&gt;
&lt;li&gt;For each meeting &lt;code&gt;[p1, p2, current_time]&lt;/code&gt; in this group, perform &lt;code&gt;dsu.union(p1, p2)&lt;/code&gt;. This connects all people who meet at this specific time, forming temporary secret-sharing components.
    This step essentially creates a "snapshot" of connectivity at &lt;code&gt;current_time&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Python (within the loop from Step 4)&lt;/span&gt;
&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;
    &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;temp_people&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# To store all people involved in meetings at current_time&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;union&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Connect these people&lt;/span&gt;
        &lt;span class="n"&gt;temp_people&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;temp_people&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="c1"&gt;# ... (reset logic will go here)&lt;/span&gt;
    &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="step-6-identify-and-reset-non-secret-holders"&gt;Step 6: Identify and Reset Non-Secret Holders&lt;/h3&gt;
&lt;p&gt;This is the most critical and often misunderstood step. After all &lt;code&gt;union&lt;/code&gt; operations for a given &lt;code&gt;current_time&lt;/code&gt; are complete, we have a temporary network of connections. Now, we need to determine who &lt;em&gt;actually&lt;/em&gt; gains the secret at this time.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;For every person &lt;code&gt;p&lt;/code&gt; in &lt;code&gt;temp_people&lt;/code&gt; (i.e., everyone who participated in a meeting at &lt;code&gt;current_time&lt;/code&gt;):&lt;/li&gt;
&lt;li&gt;Check if &lt;code&gt;dsu.find(p)&lt;/code&gt; is connected to &lt;code&gt;dsu.find(0)&lt;/code&gt; (the root of the component containing person 0, who always has the secret).&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;dsu.find(p) != dsu.find(0)&lt;/code&gt;, it means person &lt;code&gt;p&lt;/code&gt; is &lt;em&gt;not&lt;/em&gt; connected to anyone who definitely holds the secret &lt;em&gt;at this &lt;code&gt;current_time&lt;/code&gt;&lt;/em&gt;. Despite meeting others and forming temporary connections, &lt;code&gt;p&lt;/code&gt; does not learn the secret yet.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;p&lt;/code&gt; does not learn the secret, their connections formed &lt;em&gt;only&lt;/em&gt; within this &lt;code&gt;current_time&lt;/code&gt; group should not carry over to future time steps if they didn't lead to secret acquisition. To achieve this, we &lt;em&gt;reset&lt;/em&gt; their DSU state. This means setting &lt;code&gt;dsu.parent[p] = p&lt;/code&gt; and potentially &lt;code&gt;dsu.rank[p] = 0&lt;/code&gt; (or &lt;code&gt;dsu.size[p] = 1&lt;/code&gt;). This effectively isolates them back into their own set, unless they are re-connected to someone who does know the secret in a future meeting.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Why this reset is necessary:&lt;/strong&gt; Imagine people A and B meet at &lt;code&gt;t=5&lt;/code&gt;. Neither knows the secret. They connect in DSU. Later, at &lt;code&gt;t=10&lt;/code&gt;, A meets C, who knows the secret. A learns the secret. If we don't reset, B would also incorrectly appear to know the secret because of the &lt;code&gt;A-B&lt;/code&gt; connection at &lt;code&gt;t=5&lt;/code&gt;. By resetting, we ensure that secret propagation only happens through valid paths &lt;em&gt;at the specific time of meeting&lt;/em&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Python (within the loop from Step 4, after unions)&lt;/span&gt;
    &lt;span class="c1"&gt;# ... (unions done)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;person&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;temp_people&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="c1"&gt;# This person does not know the secret through any path to person 0 at this time.&lt;/span&gt;
            &lt;span class="c1"&gt;# Reset their DSU state so their &amp;quot;potential&amp;quot; connection is broken for future meetings.&lt;/span&gt;
            &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;person&lt;/span&gt;
            &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="c1"&gt;# If using rank optimization&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="step-7-collect-all-secret-holders"&gt;Step 7: Collect All Secret Holders&lt;/h3&gt;
&lt;p&gt;After iterating through all meetings across all time steps, the DSU structure will accurately reflect who is connected to the initial secret holders (person &lt;code&gt;0&lt;/code&gt;).&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Iterate from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For each person &lt;code&gt;i&lt;/code&gt;, if &lt;code&gt;dsu.find(i) == dsu.find(0)&lt;/code&gt;, then person &lt;code&gt;i&lt;/code&gt; knows the secret.&lt;/li&gt;
&lt;li&gt;Add all such persons &lt;code&gt;i&lt;/code&gt; to your result list.&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;# Python (after the main loop)&lt;/span&gt;
&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This step-by-step approach ensures that the time-dependent nature of secret sharing is correctly handled, leading to an accurate and efficient solution for the 2092. Find All People With Secret leetcode question in c++, python,java.&lt;/p&gt;
&lt;h2 id="code-implementation-for-find-all-people-with-secret"&gt;Code Implementation for "Find All People With Secret"&lt;/h2&gt;
&lt;p&gt;Here are complete implementations of the solution using C++, Python, and Java, demonstrating the DSU structure and the time-based processing logic.&lt;/p&gt;
&lt;h3 id="python-solution"&gt;Python Solution&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Finds the representative of the set containing i with path compression.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;union&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Unites the sets containing i and j, using union by rank.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="n"&gt;root_i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;root_j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;root_i&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;root_j&lt;/span&gt;
            &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;root_i&lt;/span&gt;
            &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;root_i&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;Resets person i to be in their own set.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;findAllPeople&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]],&lt;/span&gt; &lt;span class="n"&gt;firstPerson&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
        &lt;span class="c1"&gt;# Step 1 &amp;amp; 2: Initialize DSU and connect 0 and firstPerson&lt;/span&gt;
        &lt;span class="n"&gt;dsu&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;union&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;firstPerson&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 3: Sort meetings by time&lt;/span&gt;
        &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

        &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;
            &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

            &lt;span class="c1"&gt;# Collect all people who meet at current_time&lt;/span&gt;
            &lt;span class="c1"&gt;# and perform unions for all meetings at this time.&lt;/span&gt;
            &lt;span class="n"&gt;temp_people_at_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;union&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;temp_people_at_time&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;temp_people_at_time&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

            &lt;span class="c1"&gt;# Step 4: After all unions for current_time, check who truly knows the secret&lt;/span&gt;
            &lt;span class="c1"&gt;# and reset those who don&amp;#39;t.&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;person&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;temp_people_at_time&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                    &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Person does not know the secret yet; reset their connections.&lt;/span&gt;

            &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="c1"&gt;# Move to the next group of meetings&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 5: Collect all people who know the secret&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="c-solution"&gt;C++ Solution&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;numeric&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;algorithm&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;set&amp;gt;&lt;/span&gt;

&lt;span class="c1"&gt;// DSU (Disjoint Set Union) class&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;DSU&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;iota&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;begin&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// parent[i] = i&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;assign&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// rank[i] = 0&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Path compression&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;unite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Union by rank&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;findAllPeople&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;firstPerson&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 1 &amp;amp; 2: Initialize DSU and connect 0 and firstPerson&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;unite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;firstPerson&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 3: Sort meetings by time&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;begin&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[](&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Collect all people who meet at current_time&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// and perform unions for all meetings at this time.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;set&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;temp_people_at_time&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;unite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;temp_people_at_time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;temp_people_at_time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Step 4: After all unions for current_time, check who truly knows the secret&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// and reset those who don&amp;#39;t.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;temp_people_at_time&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Person does not know the secret yet; reset their connections.&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Move to the next group of meetings&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 5: Collect all people who know the secret&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="java-solution"&gt;Java Solution&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.*&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// DSU (Disjoint Set Union) class&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DSU&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Path compression&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;unite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Union by rank&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;root_i&lt;/span&gt;&lt;span class="o"&gt;]++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;findAllPeople&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;firstPerson&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 1 &amp;amp; 2: Initialize DSU and connect 0 and firstPerson&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;DSU&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;unite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;firstPerson&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 3: Sort meetings by time&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;compare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Collect all people who meet at current_time&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// and perform unions for all meetings at this time.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;Set&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tempPeopleAtTime&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;HashSet&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;meetings&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;unite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;tempPeopleAtTime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;tempPeopleAtTime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Step 4: After all unions for current_time, check who truly knows the secret&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// and reset those who don&amp;#39;t.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tempPeopleAtTime&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;reset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;person&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Person does not know the secret yet; reset their connections.&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Move to the next group of meetings&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 5: Collect all people who know the secret&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dsu&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &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;h2 id="time-and-space-complexity-analysis-for-2092-find-all-people-with-secret-leetcode-solution"&gt;Time and Space Complexity Analysis for 2092. Find All People With Secret LeetCode Solution&lt;/h2&gt;
&lt;p&gt;Understanding the performance characteristics of the solution is crucial, especially in competitive programming contexts. The DSU-based approach provides an efficient solution for the 2092. Find All People With Secret leetcode question in c++, python,java.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;Let &lt;code&gt;N&lt;/code&gt; be the number of people and &lt;code&gt;M&lt;/code&gt; be the number of meetings.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Sorting Meetings:&lt;/strong&gt; Sorting the &lt;code&gt;meetings&lt;/code&gt; array takes &lt;code&gt;O(M log M)&lt;/code&gt; time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DSU Initialization:&lt;/strong&gt; Initializing the &lt;code&gt;parent&lt;/code&gt; and &lt;code&gt;rank&lt;/code&gt; arrays takes &lt;code&gt;O(N)&lt;/code&gt; time. The initial &lt;code&gt;union(0, firstPerson)&lt;/code&gt; takes amortized &lt;code&gt;O(alpha(N))&lt;/code&gt; time, where &lt;code&gt;alpha&lt;/code&gt; is the inverse Ackermann function, which is practically a constant (less than 5 for any realistic &lt;code&gt;N&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Processing Meetings:&lt;/strong&gt; We iterate through the sorted meetings once.&lt;ul&gt;
&lt;li&gt;For each group of meetings at &lt;code&gt;current_time&lt;/code&gt;, we perform &lt;code&gt;union&lt;/code&gt; operations for each meeting. There are &lt;code&gt;M&lt;/code&gt; total meetings, so &lt;code&gt;M&lt;/code&gt; &lt;code&gt;union&lt;/code&gt; operations are performed across all time steps. Each &lt;code&gt;union&lt;/code&gt; operation (with path compression and union by rank/size) takes amortized &lt;code&gt;O(alpha(N))&lt;/code&gt; time. Total &lt;code&gt;O(M * alpha(N))&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For each group, we iterate through the unique people involved (&lt;code&gt;temp_people_at_time&lt;/code&gt;) to perform &lt;code&gt;find&lt;/code&gt; and potentially &lt;code&gt;reset&lt;/code&gt; operations. A person &lt;code&gt;P&lt;/code&gt; can be added to &lt;code&gt;temp_people_at_time&lt;/code&gt; at most &lt;code&gt;N&lt;/code&gt; times if they meet everyone at different times, but it's more tightly bounded by the total number of people involved in meetings at a specific time. In the worst case, if all &lt;code&gt;N&lt;/code&gt; people meet at the same time, this loop runs &lt;code&gt;N&lt;/code&gt; times. Across all time steps, a person could be added to &lt;code&gt;temp_people_at_time&lt;/code&gt; multiple times, and each &lt;code&gt;find&lt;/code&gt; and &lt;code&gt;reset&lt;/code&gt; operation takes amortized &lt;code&gt;O(alpha(N))&lt;/code&gt; time. The total number of &lt;code&gt;find&lt;/code&gt; and &lt;code&gt;reset&lt;/code&gt; operations for all people across all time steps is bounded by &lt;code&gt;O(M * alpha(N))&lt;/code&gt; (since each meeting introduces two people) or &lt;code&gt;O(N * alpha(N))&lt;/code&gt; for all distinct people reset, whichever is larger, but overall it doesn't exceed &lt;code&gt;O(M * alpha(N) + N * alpha(N))&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Collecting Results:&lt;/strong&gt; Iterating through all &lt;code&gt;N&lt;/code&gt; people and performing &lt;code&gt;find(k)&lt;/code&gt; takes &lt;code&gt;O(N * alpha(N))&lt;/code&gt; time.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Combining these, the dominant factor is typically the sorting step.
&lt;strong&gt;Overall Time Complexity: &lt;code&gt;O(M log M + (N + M) * alpha(N))&lt;/code&gt;&lt;/strong&gt; which simplifies to &lt;code&gt;O(M log M + N * alpha(N))&lt;/code&gt; or generally &lt;code&gt;O(M log M)&lt;/code&gt; if M is large, because &lt;code&gt;alpha(N)&lt;/code&gt; is practically constant.&lt;/p&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;DSU Arrays:&lt;/strong&gt; The &lt;code&gt;parent&lt;/code&gt; and &lt;code&gt;rank&lt;/code&gt; arrays take &lt;code&gt;O(N)&lt;/code&gt; space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Meetings Storage:&lt;/strong&gt; The input &lt;code&gt;meetings&lt;/code&gt; array takes &lt;code&gt;O(M)&lt;/code&gt; space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;temp_people_at_time&lt;/code&gt; Set:&lt;/strong&gt; In the worst case, all &lt;code&gt;N&lt;/code&gt; people could be involved in meetings at the same time, leading to &lt;code&gt;O(N)&lt;/code&gt; space for this temporary set.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Result List:&lt;/strong&gt; Stores up to &lt;code&gt;N&lt;/code&gt; integers, so &lt;code&gt;O(N)&lt;/code&gt; space.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Overall Space Complexity: &lt;code&gt;O(N + M)&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;This analysis shows that the chosen DSU-based approach is highly efficient for the given constraints, making it suitable for competitive programming environments.&lt;/p&gt;
&lt;h2 id="common-mistakes-and-best-practices-for-2092-find-all-people-with-secret-leetcode-question"&gt;Common Mistakes and Best Practices for 2092. Find All People With Secret LeetCode Question&lt;/h2&gt;
&lt;p&gt;Solving the 2092. Find All People With Secret leetcode question in c++, python,java requires careful attention to detail. Several common pitfalls can lead to incorrect or inefficient solutions. Being aware of these can help you avoid them.&lt;/p&gt;
&lt;h3 id="incorrect-dsu-initialization"&gt;Incorrect DSU Initialization&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Forgetting to initially &lt;code&gt;union(0, firstPerson)&lt;/code&gt; or initializing the DSU structure incorrectly (e.g., not setting &lt;code&gt;parent[i] = i&lt;/code&gt;).
&lt;strong&gt;Impact:&lt;/strong&gt; Person &lt;code&gt;firstPerson&lt;/code&gt; might not be recognized as a secret holder from the beginning, or the DSU might not correctly represent disjoint sets.
&lt;strong&gt;Avoidance:&lt;/strong&gt; Always double-check your DSU constructor and initial calls. Ensure &lt;code&gt;0&lt;/code&gt; and &lt;code&gt;firstPerson&lt;/code&gt; are correctly merged into the same set at the very start, reflecting their initial secret knowledge.&lt;/p&gt;
&lt;h3 id="not-sorting-meetings-by-time"&gt;Not Sorting Meetings by Time&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Processing meetings in an arbitrary order or in the order they appear in the input array without sorting by &lt;code&gt;time_i&lt;/code&gt;.
&lt;strong&gt;Impact:&lt;/strong&gt; Secret propagation logic will be fundamentally flawed. A secret might appear to be shared retroactively or through paths that aren't valid at the correct chronological moment. For example, if A meets B at &lt;code&gt;t=10&lt;/code&gt; and then A learns a secret at &lt;code&gt;t=5&lt;/code&gt;, if &lt;code&gt;t=10&lt;/code&gt; meeting is processed first, B won't learn the secret when they should.
&lt;strong&gt;Avoidance:&lt;/strong&gt; Make sorting &lt;code&gt;meetings&lt;/code&gt; by &lt;code&gt;time_i&lt;/code&gt; your absolute first step after DSU initialization. Emphasize that all meetings at a given time &lt;code&gt;t&lt;/code&gt; must be processed as a group.&lt;/p&gt;
&lt;h3 id="missing-the-reset-step"&gt;Missing the Reset Step&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; After processing all meetings at a given &lt;code&gt;current_time&lt;/code&gt; and performing &lt;code&gt;union&lt;/code&gt; operations, failing to &lt;code&gt;reset&lt;/code&gt; the DSU state for people who participated in meetings but ultimately did not get connected to &lt;code&gt;find(0)&lt;/code&gt;.
&lt;strong&gt;Impact:&lt;/strong&gt; This is perhaps the most subtle and common error. Without the reset, temporary connections formed between people who &lt;em&gt;don't&lt;/em&gt; know the secret can persist. This could lead to people falsely appearing to know the secret in future time steps if they later connect to someone who learns the secret, even if their initial path to &lt;code&gt;0&lt;/code&gt; at an earlier time was invalid.
&lt;strong&gt;Example:&lt;/strong&gt; A meets B at &lt;code&gt;t=1&lt;/code&gt;. Neither knows the secret. DSU connects A and B. If no reset, A and B are in the same component. At &lt;code&gt;t=2&lt;/code&gt;, A meets C, who knows the secret. A learns it. Without reset, B would now also appear to know it because B is connected to A, but this connection was formed at &lt;code&gt;t=1&lt;/code&gt; when A didn't know the secret.
&lt;strong&gt;Avoidance:&lt;/strong&gt; Always include the reset step. For every person &lt;code&gt;p&lt;/code&gt; involved in meetings at &lt;code&gt;current_time&lt;/code&gt;, if &lt;code&gt;dsu.find(p) != dsu.find(0)&lt;/code&gt; &lt;em&gt;after&lt;/em&gt; all unions for that &lt;code&gt;current_time&lt;/code&gt; are done, then &lt;code&gt;dsu.reset(p)&lt;/code&gt;. This breaks invalid temporary connections.&lt;/p&gt;
&lt;h3 id="inefficient-grouping-of-meetings"&gt;Inefficient Grouping of Meetings&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Iterating through meetings one by one and performing unions, rather than grouping meetings by their &lt;code&gt;time_i&lt;/code&gt; and processing them in batches.
&lt;strong&gt;Impact:&lt;/strong&gt; While not strictly incorrect, processing meetings individually can be less efficient and complicate the logic for the reset step. It's cleaner and often more performant to collect all meetings for a single timestamp, perform all unions, and then apply the reset logic.
&lt;strong&gt;Avoidance:&lt;/strong&gt; Use a &lt;code&gt;while&lt;/code&gt; loop with an inner &lt;code&gt;while&lt;/code&gt; loop (or similar logic) to process all meetings occurring at the same time in a single block, as shown in the provided solutions.&lt;/p&gt;
&lt;h3 id="off-by-one-errors-or-indexing-issues"&gt;Off-by-One Errors or Indexing Issues&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Common in array-based problems, especially when dealing with &lt;code&gt;n&lt;/code&gt; people labeled &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;. Forgetting to handle array bounds, or accidentally using 1-based indexing when 0-based is expected.
&lt;strong&gt;Impact:&lt;/strong&gt; &lt;code&gt;IndexOutOfBounds&lt;/code&gt; errors, or incorrect logic where people are mapped to the wrong DSU indices.
&lt;strong&gt;Avoidance:&lt;/strong&gt; Be vigilant about array sizes and indexing. If &lt;code&gt;n&lt;/code&gt; people are labeled &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;, your DSU array size should be &lt;code&gt;n&lt;/code&gt;. When iterating, use &lt;code&gt;range(n)&lt;/code&gt; or &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;By being mindful of these common mistakes, you can significantly improve your chances of developing a correct and robust solution for the "Find All People With Secret" problem.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the main challenge in LeetCode 2092?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The main challenge is managing time-dependent secret propagation. Meetings must be processed chronologically, and people only acquire secrets if connected to an initial holder at that specific time.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Why is Disjoint Set Union (DSU) used in this problem?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: DSU efficiently manages groups of connected people. It helps determine if a person is part of a component that includes an initial secret holder, allowing for quick union and find operations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the significance of the "reset" step in the DSU approach?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The reset step is crucial to prevent incorrect secret propagation. It ensures that temporary connections formed at a specific time are only maintained if they lead to secret acquisition, preventing invalid connections from affecting future time steps.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/find-all-people-with-secret/"&gt;LeetCode Problem 2092: Find All People With Secret&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/disjoint-set-data-structures-union-find-algorithm/"&gt;GeeksforGeeks - Disjoint Set Union (Union-Find) Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=ayW5B2WfoEQ"&gt;YouTube - William Fiset: Disjoint Set Union (Union Find) Data Structure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/"&gt;GeeksforGeeks - Graph Theory Basics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/sorting-algorithms/"&gt;GeeksforGeeks - Sorting Algorithms&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The 2092. Find All People With Secret leetcode question in c++, python,java presents a stimulating challenge that effectively tests your ability to combine sorting, graph theory concepts, and the powerful Disjoint Set Union (DSU) data structure. We've explored a comprehensive, step-by-step approach that leverages the chronological order of meetings to accurately model secret propagation. The key insights involve sorting meetings by time, using DSU to track connections, and crucially, resetting the DSU state for individuals who participate in meetings but do not acquire the secret through a valid path to an initial secret holder at that specific time.&lt;/p&gt;
&lt;p&gt;By understanding the importance of the time dimension and correctly applying DSU with path compression and union by rank/size, you can develop an efficient solution that handles the constraints effectively. The provided C++, Python, and Java implementations demonstrate how to translate this logic into robust, working code. Remember that mastering problems like "Find All People With Secret" not only enhances your algorithmic toolkit but also sharpens your problem-solving skills, preparing you for more complex challenges in competitive programming and software development. Continue to practice and apply these fundamental concepts, and you'll find yourself capable of tackling an ever- broader range of algorithmic puzzles.&lt;/p&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Java"/><category term="C Plus Plus"/><category term="LeetCode"/><category term="Coding Interview"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/find-all-people-with-secret-leetcode-2092-tutorial.webp" width="1200"/><media:title type="plain">2092. Find All People With Secret: LeetCode Tutorial in C++, Python, Java</media:title><media:description type="plain">Master LeetCode 2092. Find All People With Secret using C++, Python, and Java. This tutorial guides you through an efficient solution for this challenging gr...</media:description></entry><entry><title>Number Of Islands: A Deep Dive into Graph Traversal Algorithms</title><link href="https://analyticsdrive.tech/number-of-islands-graph-traversal-tutorial/" rel="alternate"/><published>2026-03-12T15:07:00+05:30</published><updated>2026-03-12T15:07:00+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-03-12:/number-of-islands-graph-traversal-tutorial/</id><summary type="html">&lt;p&gt;Master the classic 'Number Of Islands' problem. This tutorial explores efficient graph traversal algorithms like BFS and DFS to count distinct islands in a 2...&lt;/p&gt;</summary><content type="html">&lt;p&gt;The &lt;code&gt;Number Of Islands&lt;/code&gt; problem is a cornerstone in competitive programming and a fantastic way to solidify your understanding of graph traversal algorithms. This challenge, often presented as a grid of '1's (land) and '0's (water), asks you to count the total number of distinct islands. It's a classic problem that demands a &lt;strong&gt;deep dive&lt;/strong&gt; into how to efficiently explore connected components within a matrix, making it an excellent exercise for practicing fundamental &lt;strong&gt;graph traversal&lt;/strong&gt; techniques and designing robust &lt;strong&gt;algorithms&lt;/strong&gt;. Its widespread appearance in technical interviews underscores its importance as a fundamental test of problem-solving and algorithmic thinking. By the end of this tutorial, you'll be well-equipped to tackle similar grid-based problems with confidence and apply these traversal techniques to a broader range of challenges.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#introduction-to-the-number-of-islands-problem"&gt;Introduction to the Number Of Islands Problem&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-tackling-this-challenge"&gt;Prerequisites for Tackling this Challenge&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#basic-programming-concepts"&gt;Basic Programming Concepts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#arrays-and-matrices"&gt;Arrays and Matrices&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#recursion-for-dfs"&gt;Recursion (for DFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#basic-graph-theory-concepts"&gt;Basic Graph Theory Concepts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#problem-statement-visualizing-the-grid"&gt;Problem Statement &amp;amp; Visualizing the Grid&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-the-core-concepts-graphs-and-traversal"&gt;Understanding the Core Concepts: Graphs and Traversal&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-grid-as-an-implicit-graph"&gt;The Grid as an Implicit Graph&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#why-graph-traversal"&gt;Why Graph Traversal?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#two-primary-traversal-strategies-bfs-and-dfs"&gt;Two Primary Traversal Strategies: BFS and DFS&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#breadth-first-search-bfs"&gt;Breadth-First Search (BFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#depth-first-search-dfs"&gt;Depth-First Search (DFS)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#solving-the-number-of-islands-problem-with-bfs"&gt;Solving the Number Of Islands Problem with BFS&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-1-initialize-grid-dimensions-and-island-count"&gt;Step 1: Initialize Grid Dimensions and Island Count&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-2-iterate-through-each-cell-in-the-grid"&gt;Step 2: Iterate Through Each Cell in the Grid&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-3-initiate-bfs-from-a-land-cell"&gt;Step 3: Initiate BFS from a Land Cell&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-4-explore-neighbors-using-the-queue"&gt;Step 4: Explore Neighbors Using the Queue&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-5-mark-cells-as-visited-in-place-modification"&gt;Step 5: Mark Cells as Visited (In-place Modification)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-6-return-the-total-count"&gt;Step 6: Return the Total Count&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-code-example-bfs"&gt;Python Code Example (BFS)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#depth-first-search-dfs-approach-for-number-of-islands"&gt;Depth-First Search (DFS) Approach for Number Of Islands&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-1-initialize-grid-dimensions-and-island-count_1"&gt;Step 1: Initialize Grid Dimensions and Island Count&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-2-iterate-through-each-cell"&gt;Step 2: Iterate Through Each Cell&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-3-define-the-recursive-dfs-helper-function"&gt;Step 3: Define the Recursive DFS Helper Function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-4-implement-base-cases-and-boundary-checks-in-dfs"&gt;Step 4: Implement Base Cases and Boundary Checks in DFS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-5-mark-current-cell-as-visited"&gt;Step 5: Mark Current Cell as Visited&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-6-recursively-explore-neighbors"&gt;Step 6: Recursively Explore Neighbors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-7-return-the-total-count"&gt;Step 7: Return the Total Count&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-code-example-dfs"&gt;Python Code Example (DFS)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#complexity-analysis"&gt;Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-edge-cases"&gt;Common Mistakes and Edge Cases&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-incorrect-boundary-checks"&gt;1. Incorrect Boundary Checks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-forgetting-to-mark-visited-cells"&gt;2. Forgetting to Mark Visited Cells&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-incorrect-neighbor-definitions"&gt;3. Incorrect Neighbor Definitions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-handling-an-empty-grid"&gt;4. Handling an Empty Grid&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-grid-with-only-water-or-only-land"&gt;5. Grid with Only Water or Only Land&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#practical-applications-of-the-number-of-islands-logic"&gt;Practical Applications of the "Number Of Islands" Logic&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-image-processing-and-computer-vision"&gt;1. Image Processing and Computer Vision&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-network-analysis"&gt;2. Network Analysis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-game-development"&gt;3. Game Development&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-geographical-information-systems-gis"&gt;4. Geographical Information Systems (GIS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-circuit-design-and-vlsi"&gt;5. Circuit Design and VLSI&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6-medical-imaging"&gt;6. Medical Imaging&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#7-robotics-and-autonomous-systems"&gt;7. Robotics and Autonomous Systems&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="introduction-to-the-number-of-islands-problem"&gt;Introduction to the Number Of Islands Problem&lt;/h2&gt;
&lt;p&gt;The "Number Of Islands" problem is a popular algorithmic challenge frequently encountered in technical interviews and competitive programming contests. It presents a straightforward premise: given a 2D binary grid, where '1' represents land and '0' represents water, you need to determine the total number of islands. An island is defined as a group of '1's that are connected horizontally or vertically (not diagonally). Crucially, an island is completely surrounded by water or the boundaries of the grid.&lt;/p&gt;
&lt;p&gt;At its core, this problem is about identifying connected components in an undirected graph. Although the input is a 2D grid, we can implicitly view each land cell ('1') as a node in a graph, and two land cells are connected if they are adjacent horizontally or vertically. Counting the number of islands then translates to counting the number of disjoint connected components in this implicit graph. Solving this problem provides practical experience with Breadth-First Search (BFS) and Depth-First Search (DFS), two fundamental algorithms for traversing graphs and solving a wide array of connectivity problems. Mastering this concept is key for many grid-based or connectivity-related questions.&lt;/p&gt;
&lt;h2 id="prerequisites-for-tackling-this-challenge"&gt;Prerequisites for Tackling this Challenge&lt;/h2&gt;
&lt;p&gt;Before diving into the solution for the "Number Of Islands" problem, it's beneficial to have a foundational understanding of several key concepts. These prerequisites will ensure you can fully grasp the logic and implementation details of the algorithms we'll discuss.&lt;/p&gt;
&lt;h3 id="basic-programming-concepts"&gt;Basic Programming Concepts&lt;/h3&gt;
&lt;p&gt;You should be comfortable with:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Variables and Data Types:&lt;/strong&gt; Understanding integers, booleans, and string representations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Conditional Statements:&lt;/strong&gt; &lt;code&gt;if&lt;/code&gt;, &lt;code&gt;else if&lt;/code&gt;, &lt;code&gt;else&lt;/code&gt; for handling different scenarios and boundary conditions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Loops:&lt;/strong&gt; &lt;code&gt;for&lt;/code&gt; and &lt;code&gt;while&lt;/code&gt; loops for iterating through grids and performing repetitive actions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Functions/Methods:&lt;/strong&gt; Defining and calling functions to encapsulate logic, especially for recursive DFS.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="arrays-and-matrices"&gt;Arrays and Matrices&lt;/h3&gt;
&lt;p&gt;The problem input is a 2D grid, which is essentially a matrix or a list of lists. Familiarity with:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Accessing Elements:&lt;/strong&gt; How to retrieve values at &lt;code&gt;grid[row][col]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Iterating:&lt;/strong&gt; Looping through rows and columns to visit every cell in the grid.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Boundary Checks:&lt;/strong&gt; Understanding how to prevent "index out of bounds" errors when moving within the grid.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="recursion-for-dfs"&gt;Recursion (for DFS)&lt;/h3&gt;
&lt;p&gt;While not strictly necessary for BFS, a good grasp of recursion is vital for implementing the Depth-First Search approach elegantly.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Base Cases:&lt;/strong&gt; Identifying the conditions under which a recursive call should stop.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursive Step:&lt;/strong&gt; How the problem breaks down into smaller, similar sub-problems.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Call Stack:&lt;/strong&gt; A basic understanding of how recursive calls are managed by the system.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="basic-graph-theory-concepts"&gt;Basic Graph Theory Concepts&lt;/h3&gt;
&lt;p&gt;Although the problem doesn't explicitly give you a graph, it's an implicit graph problem. Understanding these concepts will make the solution much clearer:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Nodes (Vertices) and Edges:&lt;/strong&gt; In our case, land cells are nodes, and adjacency (horizontal/vertical) defines edges.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Connected Components:&lt;/strong&gt; A subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the larger graph. An island is a connected component.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graph Traversal:&lt;/strong&gt; The process of visiting (checking and/or updating) each vertex in a graph. For a deeper dive into other fundamental graph algorithms, consider exploring tutorials on &lt;a href="/dijkstra-algorithm-python-cpp-java-tutorial/"&gt;Dijkstra's Algorithm in Python, C++, Java&lt;/a&gt; or the &lt;a href="/bellman-ford-algorithm-python-cpp-java-tutorial/"&gt;Bellman Ford Algorithm&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Breadth-First Search (BFS):&lt;/strong&gt; An algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph) and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. It typically uses a queue.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Depth-First Search (DFS):&lt;/strong&gt; An algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root (or selects some arbitrary node as the root) and explores as far as possible along each branch before backtracking. It typically uses recursion or a stack.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Having these prerequisites in your toolkit will greatly assist you in not just solving the "Number Of Islands" problem but also in approaching a wide range of other algorithmic challenges.&lt;/p&gt;
&lt;h2 id="problem-statement-visualizing-the-grid"&gt;Problem Statement &amp;amp; Visualizing the Grid&lt;/h2&gt;
&lt;p&gt;Let's formalize the problem statement and then visualize what an island looks like on a grid.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Problem Statement:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Given an &lt;code&gt;m x n&lt;/code&gt; 2D binary grid &lt;code&gt;grid&lt;/code&gt;, which represents a map of '1's (land) and '0's (water), return the number of islands.&lt;/p&gt;
&lt;p&gt;An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Consider the following &lt;code&gt;5x4&lt;/code&gt; grid:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;1 1 1 1 0
1 1 0 1 0
1 1 0 0 0
0 0 0 0 0
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;How many islands do you see? Let's break it down.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The '1's in the top-left form a large connected component. This is one island.&lt;/li&gt;
&lt;li&gt;All other cells are '0's.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So, in this example, the answer would be &lt;strong&gt;1 island&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Let's look at another example:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Here's how we visualize the islands:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;First Island:&lt;/strong&gt; The top-left &lt;code&gt;2x2&lt;/code&gt; block of '1's forms one island.
    ```&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;    (1) (1) 0 0 0
    (1) (1) 0 0 0
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt; 0   0  1 0 0
 0   0  0 1 1
```
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Second Island:&lt;/strong&gt; The '1' at &lt;code&gt;grid[2][2]&lt;/code&gt; is isolated. It's an island by itself.
    &lt;code&gt;1  1  0  0  0
     1  1  0  0  0
     0  0 (1) 0  0
     0  0  0  1  1&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Third Island:&lt;/strong&gt; The &lt;code&gt;1x2&lt;/code&gt; block of '1's at &lt;code&gt;grid[3][3]&lt;/code&gt; and &lt;code&gt;grid[3][4]&lt;/code&gt; forms another island.
    &lt;code&gt;1  1  0  0  0
     1  1  0  0  0
     0  0  1  0  0
     0  0  0 (1) (1)&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this second example, the answer would be &lt;strong&gt;3 islands&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The key insight is that once we find a piece of land ('1'), it belongs to an island. To count that island and ensure we don't count its constituent land cells again, we must "sink" or "mark as visited" all connected land cells belonging to that island. This is where graph traversal algorithms come into play.&lt;/p&gt;
&lt;h2 id="understanding-the-core-concepts-graphs-and-traversal"&gt;Understanding the Core Concepts: Graphs and Traversal&lt;/h2&gt;
&lt;p&gt;Before diving into the specific algorithms, let's firmly establish why this grid problem can be solved using graph theory and what graph traversal entails.&lt;/p&gt;
&lt;h3 id="the-grid-as-an-implicit-graph"&gt;The Grid as an Implicit Graph&lt;/h3&gt;
&lt;p&gt;While the input is a 2D matrix, we can model it as an undirected graph.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Nodes (Vertices):&lt;/strong&gt; Each cell &lt;code&gt;(row, col)&lt;/code&gt; in the grid can be considered a node. However, we are primarily interested in land cells ('1's) as potential nodes in our graph. Water cells ('0's) serve as separators.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edges:&lt;/strong&gt; An edge exists between two land cells if they are horizontally or vertically adjacent. For example, if &lt;code&gt;grid[r][c]&lt;/code&gt; is '1', it has potential edges to &lt;code&gt;grid[r-1][c]&lt;/code&gt;, &lt;code&gt;grid[r+1][c]&lt;/code&gt;, &lt;code&gt;grid[r][c-1]&lt;/code&gt;, and &lt;code&gt;grid[r][c+1]&lt;/code&gt;, provided these neighbors are also land cells ('1') and within the grid boundaries.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The goal then becomes to find the number of &lt;strong&gt;connected components&lt;/strong&gt; in this implicit graph. Each connected component of '1's forms a distinct island.&lt;/p&gt;
&lt;h3 id="why-graph-traversal"&gt;Why Graph Traversal?&lt;/h3&gt;
&lt;p&gt;Graph traversal algorithms are designed to systematically visit every node and edge in a graph. For the "Number Of Islands" problem, traversal is essential for two main reasons:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Identifying all parts of an island:&lt;/strong&gt; Once you find a '1', you need to explore all adjacent '1's to determine the full extent of that island. This process of exploration ensures that all connected land cells are grouped together.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Preventing re-counting:&lt;/strong&gt; After discovering and exploring an entire island, you need a mechanism to mark all its constituent land cells as "visited." This prevents them from being counted again when the main loop iterates to another part of the grid and encounters a cell belonging to an already counted island.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="two-primary-traversal-strategies-bfs-and-dfs"&gt;Two Primary Traversal Strategies: BFS and DFS&lt;/h3&gt;
&lt;p&gt;Both Breadth-First Search (BFS) and Depth-First Search (DFS) are suitable for this task. They differ in their exploration strategy:&lt;/p&gt;
&lt;h4 id="breadth-first-search-bfs"&gt;Breadth-First Search (BFS)&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Strategy:&lt;/strong&gt; Explores layer by layer. It starts at a source node, visits all its immediate neighbors, then visits all their unvisited neighbors, and so on.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Analogy:&lt;/strong&gt; Imagine ripples expanding outwards in a pond from a dropped stone.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Implementation:&lt;/strong&gt; Typically uses a &lt;strong&gt;queue&lt;/strong&gt; to store nodes to visit. When a node is visited, it's added to the queue, and its unvisited neighbors are added to the queue for future processing.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="depth-first-search-dfs"&gt;Depth-First Search (DFS)&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Strategy:&lt;/strong&gt; Explores as far as possible along each branch before backtracking.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Analogy:&lt;/strong&gt; Walking through a maze; you go down one path until you hit a dead end, then backtrack and try another path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Implementation:&lt;/strong&gt; Typically uses &lt;strong&gt;recursion&lt;/strong&gt; (which implicitly uses the call stack) or an explicit &lt;strong&gt;stack&lt;/strong&gt; data structure. When a node is visited, its unvisited neighbor is visited next, and the current path is explored deeply.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For the "Number Of Islands" problem, both algorithms yield the correct result. The choice between BFS and DFS often comes down to personal preference or specific constraints of related problems. For a more specialized application of these techniques, see our guide on &lt;a href="/topological-sort-dfs-bfs-python-cpp-java/"&gt;Topological Sort using DFS &amp;amp; BFS in Python, C++, Java&lt;/a&gt;. We will explore both in detail.&lt;/p&gt;
&lt;h2 id="solving-the-number-of-islands-problem-with-bfs"&gt;Solving the Number Of Islands Problem with BFS&lt;/h2&gt;
&lt;p&gt;Breadth-First Search (BFS) is an excellent choice for finding connected components. It systematically explores all reachable cells layer by layer from a starting point.&lt;/p&gt;
&lt;p&gt;Let's outline the steps and then look at the Python implementation.&lt;/p&gt;
&lt;h3 id="step-1-initialize-grid-dimensions-and-island-count"&gt;Step 1: Initialize Grid Dimensions and Island Count&lt;/h3&gt;
&lt;p&gt;First, determine the dimensions of the grid (&lt;code&gt;rows&lt;/code&gt; and &lt;code&gt;cols&lt;/code&gt;). Initialize a counter for &lt;code&gt;num_islands&lt;/code&gt; to zero. We also need a way to mark visited cells to avoid cycles and redundant processing. We can modify the grid in-place (changing '1's to '0's as we visit them) or use a separate &lt;code&gt;visited&lt;/code&gt; 2D array/set. For simplicity and often better performance, in-place modification is common in this problem.&lt;/p&gt;
&lt;h3 id="step-2-iterate-through-each-cell-in-the-grid"&gt;Step 2: Iterate Through Each Cell in the Grid&lt;/h3&gt;
&lt;p&gt;Use nested loops to traverse every cell &lt;code&gt;(r, c)&lt;/code&gt; in the grid.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;grid[r][c]&lt;/code&gt; is '1' (land), it means we've found a new, unvisited piece of an island.&lt;/li&gt;
&lt;li&gt;Increment &lt;code&gt;num_islands&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Start a BFS traversal from this cell to explore and "sink" all connected land cells belonging to this island.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-3-initiate-bfs-from-a-land-cell"&gt;Step 3: Initiate BFS from a Land Cell&lt;/h3&gt;
&lt;p&gt;When a new land cell &lt;code&gt;(r, c)&lt;/code&gt; is found, add it to a queue and immediately mark it as visited (e.g., change &lt;code&gt;grid[r][c]&lt;/code&gt; to '0').&lt;/p&gt;
&lt;h3 id="step-4-explore-neighbors-using-the-queue"&gt;Step 4: Explore Neighbors Using the Queue&lt;/h3&gt;
&lt;p&gt;While the queue is not empty:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Dequeue a cell &lt;code&gt;(current_r, current_c)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Check its four cardinal neighbors (up, down, left, right): &lt;code&gt;(current_r-1, current_c)&lt;/code&gt;, &lt;code&gt;(current_r+1, current_c)&lt;/code&gt;, &lt;code&gt;(current_r, current_c-1)&lt;/code&gt;, &lt;code&gt;(current_r, current_c+1)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For each neighbor:&lt;ul&gt;
&lt;li&gt;Ensure it's within grid boundaries.&lt;/li&gt;
&lt;li&gt;Ensure it's a land cell ('1') and hasn't been visited yet (if using a separate visited set).&lt;/li&gt;
&lt;li&gt;If it meets these conditions, change it to '0' (mark as visited) and enqueue it.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-5-mark-cells-as-visited-in-place-modification"&gt;Step 5: Mark Cells as Visited (In-place Modification)&lt;/h3&gt;
&lt;p&gt;As soon as a land cell &lt;code&gt;grid[r][c]&lt;/code&gt; is added to the queue, change its value to '0'. This effectively "sinks" the land and ensures it won't be counted again or processed by another BFS call.&lt;/p&gt;
&lt;h3 id="step-6-return-the-total-count"&gt;Step 6: Return the Total Count&lt;/h3&gt;
&lt;p&gt;After the loops complete, &lt;code&gt;num_islands&lt;/code&gt; will hold the total count of distinct islands.&lt;/p&gt;
&lt;h3 id="python-code-example-bfs"&gt;Python Code Example (BFS)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;collections&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;numIslands&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

        &lt;span class="n"&gt;rows&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;cols&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="n"&gt;num_islands&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

        &lt;span class="c1"&gt;# Define possible directions for neighbors (up, down, left, right)&lt;/span&gt;
        &lt;span class="n"&gt;directions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;

        &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;bfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="n"&gt;q&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;0&amp;#39;&lt;/span&gt; &lt;span class="c1"&gt;# Mark as visited/sunk&lt;/span&gt;

            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;curr_r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;curr_c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;popleft&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

                &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;dr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;directions&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;next_r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;next_c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;curr_r&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;curr_c&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt;

                    &lt;span class="c1"&gt;# Check boundaries and if it&amp;#39;s land&lt;/span&gt;
                    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;next_r&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;rows&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;next_c&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;cols&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;next_r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;next_c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;1&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                        &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;next_r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;next_c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;0&amp;#39;&lt;/span&gt; &lt;span class="c1"&gt;# Mark as visited/sunk&lt;/span&gt;
                        &lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;next_r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;next_c&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cols&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;1&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;num_islands&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                    &lt;span class="n"&gt;bfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Start BFS to sink the entire island&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;num_islands&lt;/span&gt;

&lt;span class="c1"&gt;# Example Usage:&lt;/span&gt;
&lt;span class="c1"&gt;# grid1 = [&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;]&lt;/span&gt;
&lt;span class="c1"&gt;# ]&lt;/span&gt;
&lt;span class="c1"&gt;# print(Solution().numIslands(grid1)) # Output: 1&lt;/span&gt;

&lt;span class="c1"&gt;# grid2 = [&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;]&lt;/span&gt;
&lt;span class="c1"&gt;# ]&lt;/span&gt;
&lt;span class="c1"&gt;# print(Solution().numIslands(grid2)) # Output: 3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;BFS Walkthrough with Example Grid:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let's use &lt;code&gt;grid2&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialize &lt;code&gt;num_islands = 0&lt;/code&gt;&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Outer loops start at &lt;code&gt;(0,0)&lt;/code&gt;. &lt;code&gt;grid[0][0]&lt;/code&gt; is '1'.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Increment &lt;code&gt;num_islands&lt;/code&gt; to &lt;code&gt;1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;bfs(0,0)&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Queue &lt;code&gt;q = [(0,0)]&lt;/code&gt;. &lt;code&gt;grid[0][0]&lt;/code&gt; becomes '0'.&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;(0,0)&lt;/code&gt;. Neighbors:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;(0,1)&lt;/code&gt;: '1'. Change &lt;code&gt;grid[0][1]&lt;/code&gt; to '0'. Enqueue &lt;code&gt;(0,1)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;(1,0)&lt;/code&gt;: '1'. Change &lt;code&gt;grid[1][0]&lt;/code&gt; to '0'. Enqueue &lt;code&gt;(1,0)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;(0,1)&lt;/code&gt;. Neighbors:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;(0,0)&lt;/code&gt;: '0' (already visited).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;(1,1)&lt;/code&gt;: '1'. Change &lt;code&gt;grid[1][1]&lt;/code&gt; to '0'. Enqueue &lt;code&gt;(1,1)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;(1,0)&lt;/code&gt;. Neighbors:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;(0,0)&lt;/code&gt;: '0'.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;(1,1)&lt;/code&gt;: '0' (already visited).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;(1,1)&lt;/code&gt;. Neighbors:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;(0,1)&lt;/code&gt;: '0'.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;(1,0)&lt;/code&gt;: '0'.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Queue is empty. &lt;code&gt;bfs(0,0)&lt;/code&gt; ends.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Current grid state:
    &lt;code&gt;0 0 0 0 0
    0 0 0 0 0
    0 0 1 0 0
    0 0 0 1 1&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Outer loops continue. Many cells are '0'.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;At &lt;code&gt;(2,2)&lt;/code&gt;, &lt;code&gt;grid[2][2]&lt;/code&gt; is '1'.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Increment &lt;code&gt;num_islands&lt;/code&gt; to &lt;code&gt;2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;bfs(2,2)&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Queue &lt;code&gt;q = [(2,2)]&lt;/code&gt;. &lt;code&gt;grid[2][2]&lt;/code&gt; becomes '0'.&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;(2,2)&lt;/code&gt;. No '1' neighbors.&lt;/li&gt;
&lt;li&gt;Queue empty. &lt;code&gt;bfs(2,2)&lt;/code&gt; ends.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Current grid state:
    &lt;code&gt;0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0
    0 0 0 1 1&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Outer loops continue.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;At &lt;code&gt;(3,3)&lt;/code&gt;, &lt;code&gt;grid[3][3]&lt;/code&gt; is '1'.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Increment &lt;code&gt;num_islands&lt;/code&gt; to &lt;code&gt;3&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;bfs(3,3)&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Queue &lt;code&gt;q = [(3,3)]&lt;/code&gt;. &lt;code&gt;grid[3][3]&lt;/code&gt; becomes '0'.&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;(3,3)&lt;/code&gt;. Neighbors:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;(3,4)&lt;/code&gt;: '1'. Change &lt;code&gt;grid[3][4]&lt;/code&gt; to '0'. Enqueue &lt;code&gt;(3,4)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Dequeue &lt;code&gt;(3,4)&lt;/code&gt;. No '1' neighbors.&lt;/li&gt;
&lt;li&gt;Queue empty. &lt;code&gt;bfs(3,3)&lt;/code&gt; ends.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Current grid state:
    &lt;code&gt;0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Outer loops finish. Return &lt;code&gt;num_islands = 3&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="depth-first-search-dfs-approach-for-number-of-islands"&gt;Depth-First Search (DFS) Approach for Number Of Islands&lt;/h2&gt;
&lt;p&gt;Depth-First Search (DFS) provides an alternative yet equally effective method for solving the "Number Of Islands" problem. Instead of using a queue, DFS leverages recursion (or an explicit stack) to explore as deeply as possible along each path before backtracking.&lt;/p&gt;
&lt;h3 id="step-1-initialize-grid-dimensions-and-island-count_1"&gt;Step 1: Initialize Grid Dimensions and Island Count&lt;/h3&gt;
&lt;p&gt;Similar to BFS, get the &lt;code&gt;rows&lt;/code&gt; and &lt;code&gt;cols&lt;/code&gt; of the grid and initialize &lt;code&gt;num_islands = 0&lt;/code&gt;. We will also use in-place modification of the grid to mark visited land cells as '0'.&lt;/p&gt;
&lt;h3 id="step-2-iterate-through-each-cell"&gt;Step 2: Iterate Through Each Cell&lt;/h3&gt;
&lt;p&gt;Loop through every cell &lt;code&gt;(r, c)&lt;/code&gt; in the grid using nested &lt;code&gt;for&lt;/code&gt; loops.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;grid[r][c]&lt;/code&gt; is '1' (land), it signifies the discovery of a new, unvisited island.&lt;/li&gt;
&lt;li&gt;Increment &lt;code&gt;num_islands&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Call a recursive &lt;code&gt;dfs&lt;/code&gt; helper function, starting from this cell, to explore and "sink" all connected land cells belonging to this island.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-3-define-the-recursive-dfs-helper-function"&gt;Step 3: Define the Recursive DFS Helper Function&lt;/h3&gt;
&lt;p&gt;Create a helper function, say &lt;code&gt;dfs(r, c)&lt;/code&gt;, which will perform the depth-first traversal. This function will take the current row and column as arguments.&lt;/p&gt;
&lt;h3 id="step-4-implement-base-cases-and-boundary-checks-in-dfs"&gt;Step 4: Implement Base Cases and Boundary Checks in DFS&lt;/h3&gt;
&lt;p&gt;Inside the &lt;code&gt;dfs&lt;/code&gt; function, immediately check for base cases and boundary conditions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Out of Bounds:&lt;/strong&gt; If &lt;code&gt;r&lt;/code&gt; or &lt;code&gt;c&lt;/code&gt; are outside the grid dimensions (&lt;code&gt;0 &amp;lt;= r &amp;lt; rows&lt;/code&gt; and &lt;code&gt;0 &amp;lt;= c &amp;lt; cols&lt;/code&gt;), return immediately.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Water or Already Visited:&lt;/strong&gt; If &lt;code&gt;grid[r][c]&lt;/code&gt; is '0' (water) or has already been marked as visited (changed to '0' during a previous traversal), return immediately.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These checks prevent infinite recursion and ensure we only process valid, unvisited land cells.&lt;/p&gt;
&lt;h3 id="step-5-mark-current-cell-as-visited"&gt;Step 5: Mark Current Cell as Visited&lt;/h3&gt;
&lt;p&gt;If the current cell &lt;code&gt;(r, c)&lt;/code&gt; is a valid, unvisited land cell, mark it as visited by changing &lt;code&gt;grid[r][c]&lt;/code&gt; to '0'. This is crucial to prevent re-visiting this cell and causing infinite loops in the recursion.&lt;/p&gt;
&lt;h3 id="step-6-recursively-explore-neighbors"&gt;Step 6: Recursively Explore Neighbors&lt;/h3&gt;
&lt;p&gt;After marking the current cell as visited, recursively call &lt;code&gt;dfs&lt;/code&gt; for all its four cardinal neighbors:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dfs(r + 1, c)&lt;/code&gt; (down)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(r - 1, c)&lt;/code&gt; (up)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(r, c + 1)&lt;/code&gt; (right)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(r, c - 1)&lt;/code&gt; (left)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The recursive calls will continue to explore deeper into the island until all connected land cells are visited and marked.&lt;/p&gt;
&lt;h3 id="step-7-return-the-total-count"&gt;Step 7: Return the Total Count&lt;/h3&gt;
&lt;p&gt;Once the outer loops have finished iterating through the entire grid, &lt;code&gt;num_islands&lt;/code&gt; will contain the final count of distinct islands.&lt;/p&gt;
&lt;h3 id="python-code-example-dfs"&gt;Python Code Example (DFS)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;numIslands&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

        &lt;span class="n"&gt;rows&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;cols&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="n"&gt;num_islands&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

        &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="c1"&gt;# Base cases: out of bounds, or water, or already visited land&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;rows&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;cols&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;0&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt;

            &lt;span class="c1"&gt;# Mark current cell as visited by changing &amp;#39;1&amp;#39; to &amp;#39;0&amp;#39;&lt;/span&gt;
            &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;0&amp;#39;&lt;/span&gt;

            &lt;span class="c1"&gt;# Recursively explore all four cardinal neighbors&lt;/span&gt;
            &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Down&lt;/span&gt;
            &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Up&lt;/span&gt;
            &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Right&lt;/span&gt;
            &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Left&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cols&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;1&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;num_islands&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                    &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Start DFS to sink the entire island&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;num_islands&lt;/span&gt;

&lt;span class="c1"&gt;# Example Usage:&lt;/span&gt;
&lt;span class="c1"&gt;# grid1 = [&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;]&lt;/span&gt;
&lt;span class="c1"&gt;# ]&lt;/span&gt;
&lt;span class="c1"&gt;# print(Solution().numIslands(grid1)) # Output: 1&lt;/span&gt;

&lt;span class="c1"&gt;# grid2 = [&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;],&lt;/span&gt;
&lt;span class="c1"&gt;#     [&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;0&amp;quot;,&amp;quot;1&amp;quot;,&amp;quot;1&amp;quot;]&lt;/span&gt;
&lt;span class="c1"&gt;# ]&lt;/span&gt;
&lt;span class="c1"&gt;# print(Solution().numIslands(grid2)) # Output: 3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;DFS Walkthrough with Example Grid:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Let's use &lt;code&gt;grid2&lt;/code&gt; again:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialize &lt;code&gt;num_islands = 0&lt;/code&gt;&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Outer loops start at &lt;code&gt;(0,0)&lt;/code&gt;. &lt;code&gt;grid[0][0]&lt;/code&gt; is '1'.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Increment &lt;code&gt;num_islands&lt;/code&gt; to &lt;code&gt;1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;dfs(0,0)&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Inside &lt;code&gt;dfs(0,0)&lt;/code&gt;: &lt;code&gt;grid[0][0]&lt;/code&gt; becomes '0'.&lt;/li&gt;
&lt;li&gt;Recursive calls: &lt;code&gt;dfs(1,0)&lt;/code&gt;, &lt;code&gt;dfs(-1,0)&lt;/code&gt; (out of bounds), &lt;code&gt;dfs(0,1)&lt;/code&gt;, &lt;code&gt;dfs(0,-1)&lt;/code&gt; (out of bounds).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(1,0)&lt;/code&gt;: &lt;code&gt;grid[1][0]&lt;/code&gt; is '1'. &lt;code&gt;grid[1][0]&lt;/code&gt; becomes '0'.&lt;ul&gt;
&lt;li&gt;Recursive calls: &lt;code&gt;dfs(2,0)&lt;/code&gt; (water), &lt;code&gt;dfs(0,0)&lt;/code&gt; (visited), &lt;code&gt;dfs(1,1)&lt;/code&gt;, &lt;code&gt;dfs(1,-1)&lt;/code&gt; (out of bounds).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(1,1)&lt;/code&gt;: &lt;code&gt;grid[1][1]&lt;/code&gt; is '1'. &lt;code&gt;grid[1][1]&lt;/code&gt; becomes '0'.&lt;ul&gt;
&lt;li&gt;Recursive calls: &lt;code&gt;dfs(2,1)&lt;/code&gt; (water), &lt;code&gt;dfs(0,1)&lt;/code&gt; (visited), &lt;code&gt;dfs(1,2)&lt;/code&gt; (water), &lt;code&gt;dfs(1,0)&lt;/code&gt; (visited).&lt;/li&gt;
&lt;li&gt;All neighbors are water or visited. &lt;code&gt;dfs(1,1)&lt;/code&gt; returns.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(1,0)&lt;/code&gt; finishes its calls, returns.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(0,1)&lt;/code&gt;: &lt;code&gt;grid[0][1]&lt;/code&gt; is '1'. &lt;code&gt;grid[0][1]&lt;/code&gt; becomes '0'.&lt;ul&gt;
&lt;li&gt;Recursive calls: &lt;code&gt;dfs(1,1)&lt;/code&gt; (visited), &lt;code&gt;dfs(-1,1)&lt;/code&gt; (out of bounds), &lt;code&gt;dfs(0,2)&lt;/code&gt; (water), &lt;code&gt;dfs(0,0)&lt;/code&gt; (visited).&lt;/li&gt;
&lt;li&gt;All neighbors are water or visited. &lt;code&gt;dfs(0,1)&lt;/code&gt; returns.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(0,0)&lt;/code&gt; finishes its calls, returns.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;At this point, the first island is completely sunk, and &lt;code&gt;num_islands = 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Grid state:
    &lt;code&gt;0 0 0 0 0
    0 0 0 0 0
    0 0 1 0 0
    0 0 0 1 1&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Outer loops continue.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;At &lt;code&gt;(2,2)&lt;/code&gt;, &lt;code&gt;grid[2][2]&lt;/code&gt; is '1'.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Increment &lt;code&gt;num_islands&lt;/code&gt; to &lt;code&gt;2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;dfs(2,2)&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Inside &lt;code&gt;dfs(2,2)&lt;/code&gt;: &lt;code&gt;grid[2][2]&lt;/code&gt; becomes '0'.&lt;/li&gt;
&lt;li&gt;Recursive calls: All neighbors &lt;code&gt;(3,2)&lt;/code&gt;, &lt;code&gt;(1,2)&lt;/code&gt;, &lt;code&gt;(2,3)&lt;/code&gt;, &lt;code&gt;(2,1)&lt;/code&gt; are water.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(2,2)&lt;/code&gt; returns.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Grid state:
    &lt;code&gt;0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0
    0 0 0 1 1&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Outer loops continue.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;At &lt;code&gt;(3,3)&lt;/code&gt;, &lt;code&gt;grid[3][3]&lt;/code&gt; is '1'.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Increment &lt;code&gt;num_islands&lt;/code&gt; to &lt;code&gt;3&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;dfs(3,3)&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Inside &lt;code&gt;dfs(3,3)&lt;/code&gt;: &lt;code&gt;grid[3][3]&lt;/code&gt; becomes '0'.&lt;/li&gt;
&lt;li&gt;Recursive calls: &lt;code&gt;dfs(4,3)&lt;/code&gt; (out of bounds), &lt;code&gt;dfs(2,3)&lt;/code&gt; (water), &lt;code&gt;dfs(3,4)&lt;/code&gt;, &lt;code&gt;dfs(3,2)&lt;/code&gt; (water).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(3,4)&lt;/code&gt;: &lt;code&gt;grid[3][4]&lt;/code&gt; is '1'. &lt;code&gt;grid[3][4]&lt;/code&gt; becomes '0'.&lt;ul&gt;
&lt;li&gt;Recursive calls: All neighbors &lt;code&gt;(4,4)&lt;/code&gt; (out of bounds), &lt;code&gt;(2,4)&lt;/code&gt; (water), &lt;code&gt;(3,5)&lt;/code&gt; (out of bounds), &lt;code&gt;(3,3)&lt;/code&gt; (visited).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(3,4)&lt;/code&gt; returns.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(3,3)&lt;/code&gt; finishes its calls, returns.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Grid state:
    &lt;code&gt;0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Outer loops finish. Return &lt;code&gt;num_islands = 3&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Both BFS and DFS effectively achieve the same goal, differing mainly in their traversal order and the data structure/mechanism used for exploration.&lt;/p&gt;
&lt;h2 id="complexity-analysis"&gt;Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the time and space complexity of our solutions is crucial for evaluating their efficiency.&lt;/p&gt;
&lt;p&gt;Let &lt;code&gt;R&lt;/code&gt; be the number of rows and &lt;code&gt;C&lt;/code&gt; be the number of columns in the grid. The total number of cells in the grid is &lt;code&gt;N = R * C&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;O(R * C)&lt;/strong&gt; for both BFS and DFS.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Explanation:&lt;/strong&gt; The outermost loops iterate through each of the &lt;code&gt;R * C&lt;/code&gt; cells in the grid. For every cell that contains '1' and hasn't been visited yet, a BFS or DFS traversal is initiated. During a traversal (either BFS or DFS), each land cell belonging to that particular island is visited and processed exactly once. When a cell is visited, its value is changed from '1' to '0' (or it's added to a &lt;code&gt;visited&lt;/code&gt; set), ensuring that it will not trigger a new traversal or be processed again by the current traversal. Each visit involves checking up to four neighbors, which is a constant-time operation. Therefore, the total time complexity is directly proportional to the total number of cells in the grid, as each cell is examined a constant number of times.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;O(R * C)&lt;/strong&gt; for both BFS and DFS in the worst case.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;BFS:&lt;/strong&gt; The space complexity for BFS is determined by the maximum size of the queue. In the worst-case scenario, if the entire grid is filled with '1's, or if a very large "ring" or "spiral" shaped island exists, the queue could potentially hold almost all &lt;code&gt;R * C&lt;/code&gt; cells before they are processed. For example, in a checkerboard pattern of '1's, the queue could store approximately half the cells.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DFS:&lt;/strong&gt; For DFS, the space complexity is dictated by the maximum depth of the recursion stack. In a worst-case scenario, such as a grid where all '1's form a single, long, snake-like island that traverses the entire grid, the recursion stack could grow to a depth of &lt;code&gt;R * C&lt;/code&gt;. Each recursive call consumes stack space. If an explicit stack data structure is used for an iterative DFS implementation, it would similarly hold up to &lt;code&gt;R * C&lt;/code&gt; elements in the worst case.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;It's important to note that if we choose to use a separate &lt;code&gt;visited&lt;/code&gt; 2D boolean array instead of modifying the grid in-place, that array would also consume &lt;code&gt;O(R * C)&lt;/code&gt; space, contributing to the overall space complexity. Our current solutions, which modify the grid, primarily use auxiliary space for the queue or recursion stack.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In summary, both BFS and DFS provide efficient solutions for the "Number Of Islands" problem, with optimal time complexity and a space complexity that is directly related to the size of the input grid due to the nature of graph traversal on dense, connected components.&lt;/p&gt;
&lt;h2 id="common-mistakes-and-edge-cases"&gt;Common Mistakes and Edge Cases&lt;/h2&gt;
&lt;p&gt;When solving the "Number Of Islands" problem, it's easy to fall into common pitfalls or overlook specific scenarios. Being aware of these can save you debugging time.&lt;/p&gt;
&lt;h3 id="1-incorrect-boundary-checks"&gt;1. Incorrect Boundary Checks&lt;/h3&gt;
&lt;p&gt;This is perhaps the most frequent mistake. When exploring neighbors &lt;code&gt;(r+dr, c+dc)&lt;/code&gt;, you &lt;strong&gt;must&lt;/strong&gt; ensure &lt;code&gt;r+dr&lt;/code&gt; and &lt;code&gt;c+dc&lt;/code&gt; are within the valid range of the grid dimensions.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Forgetting to check &lt;code&gt;0 &amp;lt;= next_r &amp;lt; rows&lt;/code&gt; and &lt;code&gt;0 &amp;lt;= next_c &amp;lt; cols&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Consequence:&lt;/strong&gt; &lt;code&gt;IndexError&lt;/code&gt; (Python) or similar array out-of-bounds exceptions in other languages, leading to runtime errors.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; Always include explicit boundary checks for &lt;code&gt;next_r&lt;/code&gt; and &lt;code&gt;next_c&lt;/code&gt; before attempting to access &lt;code&gt;grid[next_r][next_c]&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-forgetting-to-mark-visited-cells"&gt;2. Forgetting to Mark Visited Cells&lt;/h3&gt;
&lt;p&gt;The core idea of preventing re-counting parts of an island relies on marking cells as visited.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Not changing &lt;code&gt;grid[r][c]&lt;/code&gt; from '1' to '0' (or not adding to a &lt;code&gt;visited&lt;/code&gt; set) when a cell is processed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Consequence:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Infinite loops/recursion:&lt;/strong&gt; If you process a cell, then its neighbor, then that neighbor's neighbor, and eventually come back to the original cell without marking it, you could get stuck in an infinite loop (BFS) or a stack overflow (DFS).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Incorrect island count:&lt;/strong&gt; An island might be counted multiple times if its cells aren't marked as visited after its first discovery.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; As soon as a land cell is added to the queue (BFS) or processed in the recursive call (DFS), change its value to '0'.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-incorrect-neighbor-definitions"&gt;3. Incorrect Neighbor Definitions&lt;/h3&gt;
&lt;p&gt;The problem statement specifies "horizontally or vertically" connected.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Including diagonal neighbors. If you consider &lt;code&gt;(r+1, c+1)&lt;/code&gt; as a neighbor, your definition of an island will expand, leading to an incorrect count and misinterpretation of the problem.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Consequence:&lt;/strong&gt; Overcounting or incorrect grouping of cells.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; Stick to the four cardinal directions: &lt;code&gt;(r+1, c)&lt;/code&gt;, &lt;code&gt;(r-1, c)&lt;/code&gt;, &lt;code&gt;(r, c+1)&lt;/code&gt;, &lt;code&gt;(r, c-1)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-handling-an-empty-grid"&gt;4. Handling an Empty Grid&lt;/h3&gt;
&lt;p&gt;An empty grid is a valid input and should be handled gracefully.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Not checking &lt;code&gt;if not grid or not grid[0]: return 0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Consequence:&lt;/strong&gt; &lt;code&gt;IndexError&lt;/code&gt; when trying to access &lt;code&gt;len(grid[0])&lt;/code&gt; or iterate through an empty grid.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; Always include an initial check at the beginning of your function.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-grid-with-only-water-or-only-land"&gt;5. Grid with Only Water or Only Land&lt;/h3&gt;
&lt;p&gt;These are specific edge cases that your algorithm should correctly handle.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Only Water (all '0's):&lt;/strong&gt; The loops will run, but &lt;code&gt;grid[r][c] == '1'&lt;/code&gt; will never be true, so &lt;code&gt;num_islands&lt;/code&gt; will remain 0, which is correct.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Only Land (all '1's):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;The first '1' encountered will increment &lt;code&gt;num_islands&lt;/code&gt; to 1.&lt;/li&gt;
&lt;li&gt;The BFS/DFS traversal starting from that cell will mark ALL other '1's in the grid as '0'.&lt;/li&gt;
&lt;li&gt;Subsequent iterations of the outer loop will find no more '1's.&lt;/li&gt;
&lt;li&gt;The result will correctly be 1.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These are good test cases to mentally walk through or include in your unit tests. By being mindful of these common mistakes and edge cases, you can build a more robust and correct solution for the "Number Of Islands" problem.&lt;/p&gt;
&lt;h2 id="practical-applications-of-the-number-of-islands-logic"&gt;Practical Applications of the "Number Of Islands" Logic&lt;/h2&gt;
&lt;p&gt;The underlying logic used to solve the "Number Of Islands" problem, particularly the concept of identifying connected components in a grid or graph, has a surprising number of real-world and computational applications across various domains. It's not just a theoretical exercise; it represents a foundational problem-solving pattern.&lt;/p&gt;
&lt;h3 id="1-image-processing-and-computer-vision"&gt;1. Image Processing and Computer Vision&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Blob Detection:&lt;/strong&gt; Algorithms similar to "Number Of Islands" are used to identify distinct regions (or "blobs") of a certain color or intensity in an image. For example, counting distinct objects in an image, segmenting different parts of an image, or analyzing cellular structures in microscopy images.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Object Recognition:&lt;/strong&gt; Identifying connected pixels that form a coherent object is a basic step in more complex object recognition and analysis systems.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-network-analysis"&gt;2. Network Analysis&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Social Network Analysis:&lt;/strong&gt; Finding groups of closely connected individuals ("communities" or "clusters") in a social network graph. Each "island" would represent a distinct community or sub-group with strong internal ties.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Computer Network Topology:&lt;/strong&gt; Determining disconnected segments of a network, identifying points of failure, or ensuring all parts of a system are reachable. An "island" could represent a subnet that is isolated from the main network due to a link failure.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-game-development"&gt;3. Game Development&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Pathfinding and Navigation:&lt;/strong&gt; In games with grid-based maps (like strategy games or RPGs), determining reachable areas for a character or unit. Connected land cells indicate traversable terrain, helping AI agents navigate game worlds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Map Generation:&lt;/strong&gt; Algorithms might use this logic to ensure generated terrains have distinct landmasses (islands!) or to assess the connectivity of different regions for gameplay balance.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Collision Detection:&lt;/strong&gt; Identifying distinct collision meshes or interactable areas in a game world to optimize physics calculations.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-geographical-information-systems-gis"&gt;4. Geographical Information Systems (GIS)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Landmass Delineation:&lt;/strong&gt; Identifying distinct geographical landmasses from satellite imagery or elevation data. This is a very direct parallel to the original problem, helping define continents, islands, and lakes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resource Management:&lt;/strong&gt; Analyzing contiguous areas of certain land types (e.g., forests, farmlands, urban zones) for planning, environmental monitoring, and management purposes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-circuit-design-and-vlsi"&gt;5. Circuit Design and VLSI&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Connectivity Verification:&lt;/strong&gt; In integrated circuit design, verifying that all components intended to be connected are indeed part of the same electrical net, and that no unintended connections or isolated components exist. This ensures the circuit functions as designed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Layout Analysis:&lt;/strong&gt; Identifying different "islands" of conductive material on a circuit board, which could indicate manufacturing defects or design flaws if they are supposed to be connected.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="6-medical-imaging"&gt;6. Medical Imaging&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tumor Detection:&lt;/strong&gt; In MRI or CT scans, identifying distinct regions of abnormal tissue growth. Connected component analysis helps delineate the boundaries and volume of tumors.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Organ Segmentation:&lt;/strong&gt; Separating different organs or anatomical structures within a scan for diagnostic or surgical planning purposes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="7-robotics-and-autonomous-systems"&gt;7. Robotics and Autonomous Systems&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Occupancy Grids:&lt;/strong&gt; Robots use grid maps (occupancy grids) to represent their environment. "Number Of Islands" logic can help identify free traversable spaces, large obstacles, or distinct navigable zones within a complex environment.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The "Number Of Islands" problem, while seemingly simple, introduces you to the powerful concept of graph connectivity. Mastering this fundamental pattern opens doors to understanding and solving complex problems in many advanced fields.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the "Number Of Islands" problem?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: It's an algorithmic challenge to count distinct groups of connected '1's (representing land) in a 2D binary grid, where '0's represent water. Land cells are considered connected if they are horizontally or vertically adjacent.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Which algorithms are suitable for solving this problem?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Both Breadth-First Search (BFS) and Depth-First Search (DFS) are highly effective for solving this problem. They systematically explore connected land cells, marking them as visited to prevent re-counting and ensure each island is identified only once.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the time complexity of the solutions?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Both BFS and DFS solutions for the "Number Of Islands" problem have a time complexity of O(R * C), where R is the number of rows and C is the number of columns in the grid. This is because each cell in the grid is visited at most once.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href="https://leetcode.com/problems/number-of-islands/"&gt;LeetCode Problem: Number of Islands&lt;/a&gt; - The original problem on LeetCode offers a platform to practice with various test cases and view community solutions.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href="https://www.geeksforgeeks.org/breadth-first-search-src-for-graph/"&gt;GeeksforGeeks - BFS Algorithm Tutorial&lt;/a&gt; and &lt;a href="https://www.geeksforgeeks.org/depth-first-search-for-a-graph/"&gt;DFS Algorithm Tutorial&lt;/a&gt; - Comprehensive guides on the fundamentals of Breadth-First Search and Depth-First Search.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href="https://ocw.mit.edu/courses/6-046j-design-and-analysis-of-algorithms-spring-2015/resources/lecture-14-graph-algorithms-bfs-dfs-shortest-paths-part-1/"&gt;MIT OpenCourseware - Graph Algorithms (MIT OCW)&lt;/a&gt; - For a more academic and in-depth understanding of graph theory and algorithms.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Connected_component_(graph_theory)"&gt;Wikipedia - Connected Component (Graph Theory)&lt;/a&gt; - Understand the mathematical definition and properties of connected components in graph theory.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These resources will help you reinforce the concepts learned here and prepare you for more advanced graph problems.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;Number Of Islands&lt;/code&gt; problem serves as an invaluable entry point into the world of graph algorithms, particularly for those new to grid-based challenges. We've explored two primary techniques—Breadth-First Search (BFS) and Depth-First Search (DFS)—demonstrating how each can effectively identify and count distinct landmasses within a 2D binary grid. Both approaches offer optimal time and space complexity, making them efficient solutions for typical problem constraints.&lt;/p&gt;
&lt;p&gt;By walking through the step-by-step implementations and understanding the underlying logic, you've gained practical experience with essential graph traversal. This problem highlights the importance of boundary checks, proper marking of visited nodes to prevent cycles and re-counting, and correctly defining neighbors. The concepts mastered here, such as finding connected components, extend far beyond just counting islands, finding applications in image processing, network analysis, game development, and more. Keep practicing with similar problems, as the ability to efficiently traverse and analyze graph-like structures is a fundamental skill for any aspiring developer or computer scientist looking to tackle complex real-world problems.&lt;/p&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Graph Theory"/><category term="Problem Solving"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/03/number-of-islands-graph-traversal-tutorial.webp" width="1200"/><media:title type="plain">Number Of Islands: A Deep Dive into Graph Traversal Algorithms</media:title><media:description type="plain">Master the classic 'Number Of Islands' problem. This tutorial explores efficient graph traversal algorithms like BFS and DFS to count distinct islands in a 2...</media:description></entry><entry><title>Minimum Spanning Tree with Prim's Algorithm: Python, Java &amp; C++</title><link href="https://analyticsdrive.tech/minimum-spanning-tree-prims-algorithm-python-java-cpp/" rel="alternate"/><published>2026-02-27T12:27:00+05:30</published><updated>2026-04-21T04:43:51.575391+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-27:/minimum-spanning-tree-prims-algorithm-python-java-cpp/</id><summary type="html">&lt;p&gt;Master the minimum spanning tree using Prim's algorithm in Python, Java, and C++. This tutorial guides you through implementation, concepts, and optimization for efficient graph solutions.&lt;/p&gt;</summary><content type="html">&lt;p&gt;Navigating the complexities of graph theory is a fundamental skill for any aspiring developer or computer science student. Among the most crucial problems in this domain is finding a Minimum Spanning Tree (MST). This tutorial will thoroughly explore how to implement the &lt;strong&gt;minimum spanning tree using Prim's algorithm in Python, Java, and C++&lt;/strong&gt;, equipping you with a robust understanding and practical coding skills. We will delve into the algorithm's mechanics, its practical applications, and provide step-by-step code examples in three popular programming languages, ensuring you can apply this powerful concept across various development environments. Mastering Prim's algorithm is key to efficiently solving a wide range of network optimization problems, making it an invaluable addition to your algorithmic toolkit.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-a-minimum-spanning-tree-mst"&gt;What is a Minimum Spanning Tree (MST)?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-prims-algorithm"&gt;Understanding Prim's Algorithm&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#how-prims-algorithm-works-a-step-by-step-breakdown"&gt;How Prim's Algorithm Works: A Step-by-Step Breakdown&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#algorithm-steps-for-prims"&gt;Algorithm Steps for Prim's&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#illustrative-example-step-by-step-prims-execution"&gt;Illustrative Example: Step-by-Step Prim's Execution&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#prerequisites"&gt;Prerequisites&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-minimum-spanning-tree-using-prims-algorithm-in-python-java-and-c"&gt;Implementing Minimum Spanning Tree using Prim's Algorithm in Python, Java, and C++&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#implementation-in-python"&gt;Implementation in Python&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-representing-the-graph"&gt;1. Representing the Graph&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-initializing-data-structures"&gt;2. Initializing Data Structures&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-prims-algorithm-function"&gt;3. Prim's Algorithm Function&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementation-in-java"&gt;Implementation in Java&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-representing-the-graph_1"&gt;1. Representing the Graph&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-example-usage-in-java"&gt;2. Example Usage in Java&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementation-in-c"&gt;Implementation in C++&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-representing-the-graph_2"&gt;1. Representing the Graph&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-how-to-avoid-them"&gt;Common Mistakes and How to Avoid Them&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-incorrect-priority-queue-management"&gt;1. Incorrect Priority Queue Management&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-forgetting-to-mark-visited-nodes"&gt;2. Forgetting to Mark Visited Nodes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-incorrectly-updating-neighbor-weights"&gt;3. Incorrectly Updating Neighbor Weights&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-handling-disconnected-graphs"&gt;4. Handling Disconnected Graphs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-off-by-one-errors-in-graph-representation"&gt;5. Off-by-One Errors in Graph Representation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6-edge-case-graph-with-one-vertex"&gt;6. Edge Case: Graph with One Vertex&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="what-is-a-minimum-spanning-tree-mst"&gt;What is a Minimum Spanning Tree (MST)?&lt;/h2&gt;
&lt;p&gt;Before diving into Prim's algorithm, let's establish a clear understanding of what a Minimum Spanning Tree is. A graph consists of vertices (nodes) and edges (connections between nodes). A &lt;em&gt;spanning tree&lt;/em&gt; of an undirected, connected, and weighted graph is a subgraph that connects all the vertices together, without any cycles, and uses the minimum possible number of edges (specifically, V-1 edges for a graph with V vertices).&lt;/p&gt;
&lt;p&gt;A &lt;em&gt;Minimum Spanning Tree&lt;/em&gt; takes this concept further by adding the element of edge weights. If each edge in the graph has a numerical weight associated with it (e.g., representing distance, cost, or time), an MST is a spanning tree where the sum of the weights of all its edges is minimized. In essence, it's the "cheapest" way to connect all vertices without forming any loops. MSTs are crucial in many real-world scenarios, from designing efficient network layouts to optimizing transportation routes and even in clustering analysis for data science. For related problems focusing on finding shortest paths within a graph, you might explore algorithms like &lt;a href="/dijkstra-algorithm-python-cpp-java-tutorial/"&gt;Dijkstra's Algorithm&lt;/a&gt; or &lt;a href="/bellman-ford-algorithm-python-cpp-java-tutorial/"&gt;Bellman-Ford Algorithm&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="understanding-prims-algorithm"&gt;Understanding Prim's Algorithm&lt;/h2&gt;
&lt;p&gt;Prim's algorithm is a greedy algorithm used to find a Minimum Spanning Tree for a weighted undirected graph. A greedy algorithm makes the locally optimal choice at each stage with the hope of finding a global optimum. Prim's algorithm operates by building the MST one edge at a time, starting from an arbitrary vertex.&lt;/p&gt;
&lt;p&gt;The core idea is simple: begin with a single vertex, and then iteratively add the cheapest edge that connects a vertex already in the growing MST to a vertex not yet in the MST. This process continues until all vertices are included in the spanning tree. At each step, Prim's algorithm selects the smallest weight edge that expands the tree without creating a cycle, thereby guaranteeing that the total weight of the chosen edges will be minimized. This makes it an efficient and intuitive method for constructing an MST.&lt;/p&gt;
&lt;h3 id="how-prims-algorithm-works-a-step-by-step-breakdown"&gt;How Prim's Algorithm Works: A Step-by-Step Breakdown&lt;/h3&gt;
&lt;p&gt;To effectively implement Prim's algorithm, it's essential to understand its systematic approach. The algorithm maintains a set of vertices already included in the MST and, at each step, selects an edge that connects a vertex in this set to a vertex outside it, ensuring that the selected edge has the minimum possible weight.&lt;/p&gt;
&lt;h3 id="algorithm-steps-for-prims"&gt;Algorithm Steps for Prim's&lt;/h3&gt;
&lt;p&gt;Here are the detailed steps for Prim's algorithm, which we will follow in our implementations:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Initialize Data Structures:&lt;/strong&gt;
    We need a way to keep track of key information. This typically involves:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;key&lt;/code&gt; array (or &lt;code&gt;distance&lt;/code&gt; array):&lt;/strong&gt; Stores the minimum weight of an edge connecting a vertex to the current MST. Initialize &lt;code&gt;key[source_vertex] = 0&lt;/code&gt; and &lt;code&gt;key[other_vertices] = infinity&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;parent&lt;/code&gt; array:&lt;/strong&gt; Stores the parent of each vertex in the MST. This helps reconstruct the tree. Initialize &lt;code&gt;parent[source_vertex] = -1&lt;/code&gt; (or null).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;inMST&lt;/code&gt; array (or &lt;code&gt;visited&lt;/code&gt; set):&lt;/strong&gt; A boolean array to mark whether a vertex is already included in the MST. Initialize all to &lt;code&gt;false&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Adjacency List:&lt;/strong&gt; Represents the graph efficiently, storing neighbors and edge weights for each vertex.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Choose a Starting Vertex:&lt;/strong&gt;
    Select an arbitrary vertex to start building the MST. It doesn't matter which one you pick; the algorithm will find the same MST (assuming the graph is connected). For simplicity, we often choose vertex 0. Set its &lt;code&gt;key&lt;/code&gt; to 0.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Iterate to Build the MST:&lt;/strong&gt;
    Repeat the following V (number of vertices) times:&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Extract the Minimum Key Vertex:&lt;/strong&gt;
    From the set of vertices not yet included in the MST (i.e., &lt;code&gt;inMST[v] == false&lt;/code&gt;), select the vertex &lt;code&gt;u&lt;/code&gt; that has the minimum &lt;code&gt;key&lt;/code&gt; value. This vertex &lt;code&gt;u&lt;/code&gt; is the next one to be added to the MST. A priority queue is an ideal data structure for efficiently finding this minimum-key vertex.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Add Vertex to MST:&lt;/strong&gt;
    Mark &lt;code&gt;u&lt;/code&gt; as &lt;code&gt;inMST[u] = true&lt;/code&gt;. This signifies that &lt;code&gt;u&lt;/code&gt; is now part of our growing Minimum Spanning Tree.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Update Neighbors' Key Values:&lt;/strong&gt;
    For each neighbor &lt;code&gt;v&lt;/code&gt; of &lt;code&gt;u&lt;/code&gt; (i.e., for every edge &lt;code&gt;(u, v)&lt;/code&gt; with weight &lt;code&gt;w&lt;/code&gt;):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;v&lt;/code&gt; is not yet in the MST (&lt;code&gt;inMST[v] == false&lt;/code&gt;) AND the edge weight &lt;code&gt;w&lt;/code&gt; is less than the current &lt;code&gt;key[v]&lt;/code&gt; value:&lt;ul&gt;
&lt;li&gt;Update &lt;code&gt;key[v] = w&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;parent[v] = u&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If using a priority queue, update &lt;code&gt;v&lt;/code&gt;'s priority or add &lt;code&gt;v&lt;/code&gt; with its new key.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Reconstruct the MST:&lt;/strong&gt;
    Once the loop finishes, the &lt;code&gt;parent&lt;/code&gt; array will contain the structure of the MST. Each &lt;code&gt;(v, parent[v])&lt;/code&gt; forms an edge in the MST, except for the starting vertex which has &lt;code&gt;parent&lt;/code&gt; as -1. The sum of all &lt;code&gt;key[v]&lt;/code&gt; values (excluding the initial 0 for the source) gives the total weight of the MST.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="illustrative-example-step-by-step-prims-execution"&gt;Illustrative Example: Step-by-Step Prim's Execution&lt;/h3&gt;
&lt;p&gt;Let's walk through a simple example to solidify your understanding. Consider a graph with 4 vertices (A, B, C, D) and the following edges:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;(A, B) weight 1&lt;/li&gt;
&lt;li&gt;(A, C) weight 3&lt;/li&gt;
&lt;li&gt;(B, C) weight 1&lt;/li&gt;
&lt;li&gt;(B, D) weight 5&lt;/li&gt;
&lt;li&gt;(C, D) weight 2&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We'll use vertex A as our starting point.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Initial State:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;key&lt;/code&gt;: [A:0, B:∞, C:∞, D:∞]&lt;/li&gt;
&lt;li&gt;&lt;code&gt;parent&lt;/code&gt;: [A:-1, B:-1, C:-1, D:-1]&lt;/li&gt;
&lt;li&gt;&lt;code&gt;inMST&lt;/code&gt;: [A:F, B:F, C:F, D:F]&lt;/li&gt;
&lt;li&gt;&lt;code&gt;PriorityQueue&lt;/code&gt;: [(0, A, None)]&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Iteration 1:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Extract (0, A, None) from PQ. &lt;code&gt;A&lt;/code&gt; is not in MST.&lt;/li&gt;
&lt;li&gt;Mark &lt;code&gt;inMST[A] = True&lt;/code&gt;. Total cost: 0. Add A to MST.&lt;/li&gt;
&lt;li&gt;Neighbors of A:&lt;ul&gt;
&lt;li&gt;B (weight 1): &lt;code&gt;inMST[B]&lt;/code&gt; is False, 1 &amp;lt; &lt;code&gt;key[B]&lt;/code&gt; (∞). Update &lt;code&gt;key[B]=1&lt;/code&gt;, &lt;code&gt;parent[B]=A&lt;/code&gt;. Add (1, B, A) to PQ.&lt;/li&gt;
&lt;li&gt;C (weight 3): &lt;code&gt;inMST[C]&lt;/code&gt; is False, 3 &amp;lt; &lt;code&gt;key[C]&lt;/code&gt; (∞). Update &lt;code&gt;key[C]=3&lt;/code&gt;, &lt;code&gt;parent[C]=A&lt;/code&gt;. Add (3, C, A) to PQ.
&lt;code&gt;PriorityQueue&lt;/code&gt;: [(1, B, A), (3, C, A)]&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Iteration 2:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Extract (1, B, A) from PQ. &lt;code&gt;B&lt;/code&gt; is not in MST.&lt;/li&gt;
&lt;li&gt;Mark &lt;code&gt;inMST[B] = True&lt;/code&gt;. Total cost: 0 + 1 = 1. Add edge (A, B, 1) to MST.&lt;/li&gt;
&lt;li&gt;Neighbors of B:&lt;ul&gt;
&lt;li&gt;A (weight 1): &lt;code&gt;inMST[A]&lt;/code&gt; is True. Skip.&lt;/li&gt;
&lt;li&gt;C (weight 1): &lt;code&gt;inMST[C]&lt;/code&gt; is False, 1 &amp;lt; &lt;code&gt;key[C]&lt;/code&gt; (3). Update &lt;code&gt;key[C]=1&lt;/code&gt;, &lt;code&gt;parent[C]=B&lt;/code&gt;. Add (1, C, B) to PQ. (Note: A new, better path to C found!)&lt;/li&gt;
&lt;li&gt;D (weight 5): &lt;code&gt;inMST[D]&lt;/code&gt; is False, 5 &amp;lt; &lt;code&gt;key[D]&lt;/code&gt; (∞). Update &lt;code&gt;key[D]=5&lt;/code&gt;, &lt;code&gt;parent[D]=B&lt;/code&gt;. Add (5, D, B) to PQ.
&lt;code&gt;PriorityQueue&lt;/code&gt;: [(1, C, B), (3, C, A), (5, D, B)] (PQ will sort by weight, so (1, C, B) is next)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Iteration 3:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Extract (1, C, B) from PQ. &lt;code&gt;C&lt;/code&gt; is not in MST.&lt;/li&gt;
&lt;li&gt;Mark &lt;code&gt;inMST[C] = True&lt;/code&gt;. Total cost: 1 + 1 = 2. Add edge (B, C, 1) to MST.&lt;/li&gt;
&lt;li&gt;Neighbors of C:&lt;ul&gt;
&lt;li&gt;A (weight 3): &lt;code&gt;inMST[A]&lt;/code&gt; is True. Skip.&lt;/li&gt;
&lt;li&gt;B (weight 1): &lt;code&gt;inMST[B]&lt;/code&gt; is True. Skip.&lt;/li&gt;
&lt;li&gt;D (weight 2): &lt;code&gt;inMST[D]&lt;/code&gt; is False, 2 &amp;lt; &lt;code&gt;key[D]&lt;/code&gt; (5). Update &lt;code&gt;key[D]=2&lt;/code&gt;, &lt;code&gt;parent[D]=C&lt;/code&gt;. Add (2, D, C) to PQ.
&lt;code&gt;PriorityQueue&lt;/code&gt;: [(2, D, C), (3, C, A), (5, D, B)] (The older (3, C, A) and (5, D, B) are now redundant but will be skipped when extracted)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Iteration 4:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Extract (2, D, C) from PQ. &lt;code&gt;D&lt;/code&gt; is not in MST.&lt;/li&gt;
&lt;li&gt;Mark &lt;code&gt;inMST[D] = True&lt;/code&gt;. Total cost: 2 + 2 = 4. Add edge (C, D, 2) to MST.&lt;/li&gt;
&lt;li&gt;Neighbors of D:&lt;ul&gt;
&lt;li&gt;B (weight 5): &lt;code&gt;inMST[B]&lt;/code&gt; is True. Skip.&lt;/li&gt;
&lt;li&gt;C (weight 2): &lt;code&gt;inMST[C]&lt;/code&gt; is True. Skip.
All vertices are now in MST.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Final MST:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Edges: (A, B, 1), (B, C, 1), (C, D, 2)
Total Weight: 4&lt;/p&gt;
&lt;p&gt;This detailed walkthrough helps to illustrate how Prim's algorithm systematically builds the MST by always picking the locally cheapest, valid edge.&lt;/p&gt;
&lt;h2 id="prerequisites"&gt;Prerequisites&lt;/h2&gt;
&lt;p&gt;To get the most out of this tutorial and successfully implement Prim's algorithm, you should have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Basic Understanding of Graph Theory:&lt;/strong&gt; Familiarity with concepts like vertices, edges, weights, connected graphs, and cycles. For examples of other graph traversal problems, consider learning about the &lt;a href="/cses-labyrinth-problem-python-java-cpp-guide/"&gt;CSES Labyrinth Problem&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Structure Knowledge:&lt;/strong&gt; A good grasp of adjacency lists (or matrices), arrays, and especially priority queues (min-heaps).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Programming Fundamentals:&lt;/strong&gt; Basic to intermediate programming skills in at least one of Python, Java, or C++, including loops, conditional statements, and custom classes/structs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Object-Oriented Programming (for Java/C++):&lt;/strong&gt; Understanding how to define and use classes and objects will be beneficial for representing graph edges or nodes.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="implementing-minimum-spanning-tree-using-prims-algorithm-in-python-java-and-c"&gt;Implementing Minimum Spanning Tree using Prim's Algorithm in Python, Java, and C++&lt;/h2&gt;
&lt;p&gt;Let's dive into the practical implementation of Prim's algorithm in our chosen languages. We will use an adjacency list to represent the graph and a priority queue to efficiently select the next minimum-weight edge.&lt;/p&gt;
&lt;h3 id="implementation-in-python"&gt;Implementation in Python&lt;/h3&gt;
&lt;p&gt;Python's &lt;code&gt;heapq&lt;/code&gt; module provides a min-heap implementation, which is perfect for our priority queue needs. We'll represent the graph using an adjacency list where each entry stores tuples of &lt;code&gt;(weight, neighbor)&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id="1-representing-the-graph"&gt;1. Representing the Graph&lt;/h4&gt;
&lt;p&gt;We'll use a dictionary of lists for the adjacency list. &lt;code&gt;graph[u]&lt;/code&gt; will contain &lt;code&gt;(weight, v)&lt;/code&gt; for all neighbors &lt;code&gt;v&lt;/code&gt; of &lt;code&gt;u&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id="2-initializing-data-structures"&gt;2. Initializing Data Structures&lt;/h4&gt;
&lt;p&gt;We'll need &lt;code&gt;min_heap&lt;/code&gt; (priority queue), &lt;code&gt;visited&lt;/code&gt; set, &lt;code&gt;min_cost_so_far&lt;/code&gt; for total MST weight, and a list to store MST edges.&lt;/p&gt;
&lt;h4 id="3-prims-algorithm-function"&gt;3. Prim's Algorithm Function&lt;/h4&gt;
&lt;p&gt;The main function will initialize the heap with a starting vertex and then iteratively extract the minimum edge.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;heapq&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;prim_mst_python&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;    Finds the Minimum Spanning Tree (MST) of a weighted undirected graph&lt;/span&gt;
&lt;span class="sd"&gt;    using Prim&amp;#39;s algorithm.&lt;/span&gt;

&lt;span class="sd"&gt;    Args:&lt;/span&gt;
&lt;span class="sd"&gt;        graph (dict): A dictionary representing the adjacency list of the graph.&lt;/span&gt;
&lt;span class="sd"&gt;                      Each key is a vertex, and its value is a list of tuples&lt;/span&gt;
&lt;span class="sd"&gt;                      (weight, neighbor). Example: {0: [(1, 1), (2, 4)], ...}&lt;/span&gt;

&lt;span class="sd"&gt;    Returns:&lt;/span&gt;
&lt;span class="sd"&gt;        tuple: A tuple containing:&lt;/span&gt;
&lt;span class="sd"&gt;            - float: The total minimum cost of the MST.&lt;/span&gt;
&lt;span class="sd"&gt;            - list: A list of tuples (u, v, weight) representing the edges in the MST.&lt;/span&gt;
&lt;span class="sd"&gt;    &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

    &lt;span class="c1"&gt;# Choose an arbitrary starting vertex (e.g., the first one in the graph keys)&lt;/span&gt;
    &lt;span class="n"&gt;start_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; 

    &lt;span class="c1"&gt;# Priority queue stores tuples: (weight, current_vertex, parent_vertex)&lt;/span&gt;
    &lt;span class="c1"&gt;# The parent_vertex is None for the start_node itself.&lt;/span&gt;
    &lt;span class="n"&gt;min_heap&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start_node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; 

    &lt;span class="c1"&gt;# Set to keep track of visited nodes (nodes included in the MST)&lt;/span&gt;
    &lt;span class="n"&gt;visited&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

    &lt;span class="c1"&gt;# List to store the edges of the MST&lt;/span&gt;
    &lt;span class="n"&gt;mst_edges&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

    &lt;span class="c1"&gt;# Total cost of the MST&lt;/span&gt;
    &lt;span class="n"&gt;min_cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;min_heap&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Extract the edge with the minimum weight&lt;/span&gt;
        &lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;parent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;min_heap&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# If the vertex is already visited, skip it (this handles duplicate entries in heap)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;continue&lt;/span&gt;

        &lt;span class="c1"&gt;# Mark the current vertex as visited (add it to the MST)&lt;/span&gt;
        &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;min_cost&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;weight&lt;/span&gt;

        &lt;span class="c1"&gt;# Add the edge to our MST if it&amp;#39;s not the starting node&amp;#39;s initial entry&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;parent&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;mst_edges&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

        &lt;span class="c1"&gt;# Explore neighbors of the newly added vertex &amp;#39;u&amp;#39;&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;edge_weight&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[]):&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="c1"&gt;# Add neighbor to the priority queue. The current vertex &amp;#39;u&amp;#39; is its parent.&lt;/span&gt;
                &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;min_heap&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge_weight&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

    &lt;span class="c1"&gt;# Check if all vertices were included (graph might be disconnected)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# If not all vertices are visited, the graph is disconnected,&lt;/span&gt;
        &lt;span class="c1"&gt;# and a single MST cannot be formed.&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Warning: Graph is disconnected. MST found for connected component only.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;min_cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mst_edges&lt;/span&gt;

&lt;span class="c1"&gt;#### 4. Example Usage in Python&lt;/span&gt;

&lt;span class="err"&gt;```&lt;/span&gt;&lt;span class="n"&gt;python&lt;/span&gt;
&lt;span class="c1"&gt;# Example graph representation (adjacency list)&lt;/span&gt;
&lt;span class="c1"&gt;# {vertex: [(weight, neighbor), ...]}&lt;/span&gt;
&lt;span class="n"&gt;graph_python_simple&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;14&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;14&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;span class="n"&gt;cost_py&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mst_py&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;prim_mst_python&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph_python_simple&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Python MST Cost: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;cost_py&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Python MST Edges:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;mst_py&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;  (&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;, &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;) - Weight: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="implementation-in-java"&gt;Implementation in Java&lt;/h3&gt;
&lt;p&gt;In Java, we'll create a custom &lt;code&gt;Edge&lt;/code&gt; class to store target vertex and weight. The graph will be an &lt;code&gt;ArrayList&lt;/code&gt; of &lt;code&gt;ArrayList&amp;lt;Edge&amp;gt;&lt;/code&gt;. Java's &lt;code&gt;PriorityQueue&lt;/code&gt; will be used for the min-heap.&lt;/p&gt;
&lt;h4 id="1-representing-the-graph_1"&gt;1. Representing the Graph&lt;/h4&gt;
&lt;p&gt;We'll define an &lt;code&gt;Edge&lt;/code&gt; class to make graph representation clear. The graph itself will be an &lt;code&gt;ArrayList&lt;/code&gt; of &lt;code&gt;ArrayList&amp;lt;Edge&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.*&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Helper class to represent an edge in the graph&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;implements&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Comparable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;source&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Added source for easier MST edge reconstruction&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;source&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;source&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;target&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="nd"&gt;@Override&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;compareTo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;compare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PrimMSTJava&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="cm"&gt;/**&lt;/span&gt;

&lt;span class="cm"&gt;     * Finds the Minimum Spanning Tree (MST) of a weighted undirected graph&lt;/span&gt;
&lt;span class="cm"&gt;     * using Prim&amp;#39;s algorithm.&lt;/span&gt;
&lt;span class="cm"&gt;     *&lt;/span&gt;

&lt;span class="cm"&gt;     * @param numVertices The total number of vertices in the graph.&lt;/span&gt;
&lt;span class="cm"&gt;     * @param adj         An adjacency list where adj[i] contains a list of Edge objects&lt;/span&gt;
&lt;span class="cm"&gt;     *                    representing connections from vertex i.&lt;/span&gt;
&lt;span class="cm"&gt;     * @return A list of Edge objects forming the MST, or an empty list if no MST.&lt;/span&gt;
&lt;span class="cm"&gt;     */&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;primMST&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Stores the minimum cost to reach a vertex from the MST&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Stores the parent of each vertex in the MST&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Tracks if a vertex is already included in the MST&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inMST&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Initialize key values to infinity, parent to -1, and inMST to false&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;fill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;MAX_VALUE&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;fill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Priority queue to store edges, ordered by weight&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Stores Edge objects: (source, target, weight)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;PriorityQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PriorityQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Start from vertex 0 (arbitrary choice)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Cost to reach starting node is 0&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Dummy edge to start, source -1 indicates no parent&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mstEdges&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgesCount&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// To track if we&amp;#39;ve added V-1 edges&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isEmpty&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgesCount&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Extract the edge with the minimum weight&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentEdge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;poll&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentEdge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentEdge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentParent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentEdge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// If the vertex is already in MST, skip it (can have multiple entries for same vertex)&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inMST&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Add vertex u to MST&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;inMST&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// If it&amp;#39;s not the dummy start edge, add it to the MST edges list&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;currentParent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;mstEdges&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;currentParent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;edgesCount&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Explore neighbors of u&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighborEdge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighborEdge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;target&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgeWeight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighborEdge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// If v is not in MST and current edge (u,v) is lighter than previous best for v&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;inMST&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgeWeight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgeWeight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Set u as parent of v&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgeWeight&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// After building, verify if MST is complete (graph connected)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If the graph is disconnected, mstEdges will contain a spanning forest for a component.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// A full MST requires edgesCount == numVertices - 1 for a connected graph.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edgesCount&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Warning: Graph might be disconnected. MST found for a connected component only.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mstEdges&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Helper to build adjacency list for undirected graph&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;buildAdjList&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// For undirected graph&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4 id="2-example-usage-in-java"&gt;2. Example Usage in Java&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Edges: {u, v, weight}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges_java&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;14&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;buildAdjList&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges_java&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mstJava&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;primMST&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;totalCostJava&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Java MST Edges:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mstJava&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;  (&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;target&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;) - Weight: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;totalCostJava&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Java MST Cost: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;totalCostJava&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="implementation-in-c"&gt;Implementation in C++&lt;/h3&gt;
&lt;p&gt;C++ offers &lt;code&gt;std::vector&lt;/code&gt; for adjacency lists and &lt;code&gt;std::priority_queue&lt;/code&gt; for the min-heap. &lt;code&gt;std::pair&lt;/code&gt; can represent edges. Note that &lt;code&gt;std::priority_queue&lt;/code&gt; is a max-heap by default, so we'll need to use &lt;code&gt;std::greater&lt;/code&gt; or negate weights to simulate a min-heap.&lt;/p&gt;
&lt;h4 id="1-representing-the-graph_2"&gt;1. Representing the Graph&lt;/h4&gt;
&lt;p&gt;We'll use &lt;code&gt;std::vector&amp;lt;std::vector&amp;lt;std::pair&amp;lt;int, int&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt; where &lt;code&gt;pair&amp;lt;int, int&amp;gt;&lt;/code&gt; stores &lt;code&gt;{neighbor, weight}&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;queue&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;limits&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // For numeric_limits&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;tuple&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt;  // For std::tuple&lt;/span&gt;

&lt;span class="c1"&gt;// Helper struct to represent an edge for the priority queue&lt;/span&gt;
&lt;span class="k"&gt;struct&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;target_node&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;source_node&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Added source for easier MST edge reconstruction&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Custom comparator for priority_queue to make it a min-heap&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Priority queue stores elements in descending order by default.&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// To get a min-heap, we either store negative weights or use std::greater.&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;operator&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;// Function to find the Minimum Spanning Tree using Prim&amp;#39;s algorithm&lt;/span&gt;
&lt;span class="c1"&gt;// Returns a pair: {total_mst_weight, list_of_mst_edges}&lt;/span&gt;
&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;pair&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;tuple&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;primMST_cpp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;pair&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{}};&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Min-priority queue: stores {weight, target_node, source_node}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Using std::greater&amp;lt;Edge&amp;gt; makes it a min-heap based on &amp;#39;weight&amp;#39;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;priority_queue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;greater&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Stores the minimum cost to reach a vertex from the MST&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;numeric_limits&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;::&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Tracks if a vertex is already included in the MST&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inMST&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Stores the parent of each vertex in the MST&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Start from vertex 0 (arbitrary choice)&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;startNode&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;startNode&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;startNode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-1&lt;/span&gt;&lt;span class="p"&gt;});&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// {weight, target, source} dummy edge to start&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;tuple&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mstEdges&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Stores {source, target, weight}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;totalMSTWeight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgesCount&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgesCount&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentEdge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;top&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentEdge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;target_node&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight_u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentEdge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;parent_u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentEdge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;source_node&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If &amp;#39;u&amp;#39; is already in MST, skip (can have multiple entries for same vertex in PQ)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inMST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Add vertex &amp;#39;u&amp;#39; to MST&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;inMST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;totalMSTWeight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight_u&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If it&amp;#39;s not the dummy start edge, add it to the MST edges list&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent_u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;mstEdges&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;emplace_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent_u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight_u&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;edgesCount&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Explore neighbors of &amp;#39;u&amp;#39;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;first&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Neighbor vertex&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgeWeight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;second&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Weight of edge (u,v)&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// If &amp;#39;v&amp;#39; is not in MST and current edge (u,v) is lighter than previous best for &amp;#39;v&amp;#39;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;inMST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgeWeight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edgeWeight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Set u as parent of v&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="n"&gt;edgeWeight&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;});&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Add this potential edge to PQ&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Check if all vertices were included (graph might be disconnected)&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edgesCount&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Warning: Graph might be disconnected. MST found for a connected component only.&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;totalMSTWeight&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mstEdges&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Helper to build adjacency list for undirected graph&lt;/span&gt;
&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;pair&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;buildAdjList_cpp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;tuple&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;pair&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;});&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// For undirected graph&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="cp"&gt;#### 2. Example Usage in C++&lt;/span&gt;

&lt;span class="err"&gt;```&lt;/span&gt;&lt;span class="n"&gt;cpp&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Edges: {u, v, weight}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;tuple&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges_cpp&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;14&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;pair&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;buildAdjList_cpp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges_cpp&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;primMST_cpp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;totalCostCpp&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;first&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;tuple&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mstCpp&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;second&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;C++ MST Cost: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;totalCostCpp&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;C++ MST Edges:&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mstCpp&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;  (&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;) - Weight: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&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;h2 id="time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the performance characteristics of Prim's algorithm is crucial for choosing the right algorithm for a given problem.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;The time complexity of Prim's algorithm largely depends on how the priority queue is implemented. This choice is critical for performance, especially with large graphs.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;With an adjacency list and a binary heap (as implemented above):&lt;/strong&gt; This is the most common and efficient implementation for general graphs.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; Setting up the &lt;code&gt;key&lt;/code&gt;, &lt;code&gt;parent&lt;/code&gt;, and &lt;code&gt;inMST&lt;/code&gt; arrays takes &lt;strong&gt;O(V)&lt;/strong&gt; time, where V is the number of vertices.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Main Loop:&lt;/strong&gt; The &lt;code&gt;while&lt;/code&gt; loop runs up to V times, as each vertex is added to the MST exactly once.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Inside the loop:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;code&gt;pq.pop()&lt;/code&gt; (extract-min operation): In a binary heap, this takes &lt;strong&gt;O(log N)&lt;/strong&gt; time, where N is the current number of elements in the priority queue. In the worst case, the PQ can hold up to &lt;code&gt;E&lt;/code&gt; edges or &lt;code&gt;V&lt;/code&gt; vertices, so it's often approximated as O(log E) or O(log V).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Neighbor exploration:&lt;/strong&gt; For each vertex &lt;code&gt;u&lt;/code&gt; added to the MST, we iterate through its adjacent edges. In total, across all V iterations, every edge in the graph &lt;code&gt;(u, v)&lt;/code&gt; is processed twice (once when &lt;code&gt;u&lt;/code&gt; is processed, and once when &lt;code&gt;v&lt;/code&gt; is processed).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pq.push()&lt;/code&gt; (insert operation): Adding a potential edge to the priority queue also takes &lt;strong&gt;O(log N)&lt;/strong&gt; time.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Overall:&lt;/strong&gt; Since there are &lt;code&gt;V&lt;/code&gt; extractions and up to &lt;code&gt;E&lt;/code&gt; insertions (each taking &lt;code&gt;log E&lt;/code&gt; time), the total time complexity is &lt;strong&gt;O(E log V)&lt;/strong&gt;. This efficiency makes it suitable for sparse graphs (where E is much smaller than V^2). For dense graphs, where E approaches V^2, this complexity approaches O(V^2 log V), which can be less efficient than the simple array scan method.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;With an adjacency matrix and a simple array scan to find the minimum key:&lt;/strong&gt; This approach is simpler to implement but less efficient for many graph types.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The algorithm iterates V times. In each iteration, it scans all V vertices to find the one with the minimum &lt;code&gt;key&lt;/code&gt; value that is not yet in the MST. This scan takes O(V) time.&lt;/li&gt;
&lt;li&gt;After adding a vertex, it then updates the &lt;code&gt;key&lt;/code&gt; values for its neighbors, which can take another O(V) time (checking all possible edges in an adjacency matrix row/column).&lt;/li&gt;
&lt;li&gt;Total time: &lt;strong&gt;O(V^2)&lt;/strong&gt;. This is often preferred for very dense graphs where E is close to V^2, as O(V^2) can be faster than O(V^2 log V).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;With an adjacency list and a Fibonacci heap (more complex, theoretical):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;While theoretically achieving &lt;strong&gt;O(E + V log V)&lt;/strong&gt;, Fibonacci heaps are complex to implement and have high constant factors, making them less practical for competitive programming or typical production environments compared to binary heaps.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For graph problems where all-pairs shortest paths are needed, the &lt;a href="/floyd-warshall-algorithm-python-java-cpp/"&gt;Floyd-Warshall Algorithm&lt;/a&gt; offers a different approach for dense graphs.&lt;/p&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;The space complexity for Prim's algorithm using an adjacency list and a binary heap is as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Adjacency List:&lt;/strong&gt; O(V + E) to store the graph structure itself, where V is the number of vertices and E is the number of edges. This is because each vertex and each edge (twice for undirected graphs) is stored.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;key&lt;/code&gt; array:&lt;/strong&gt; O(V) to store the minimum edge weight to each vertex.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;parent&lt;/code&gt; array:&lt;/strong&gt; O(V) to reconstruct the MST paths.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;inMST&lt;/code&gt; (or &lt;code&gt;visited&lt;/code&gt;) array/set:&lt;/strong&gt; O(V) to keep track of visited vertices.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Priority Queue:&lt;/strong&gt; In the worst case, the priority queue might store up to E edges (if all edges connecting to the growing MST are added before being processed). In some optimized implementations, it only stores vertices, and its size is O(V). Therefore, it's generally &lt;strong&gt;O(E)&lt;/strong&gt; or &lt;strong&gt;O(V)&lt;/strong&gt;, depending on the exact implementation details.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;MST Edges List:&lt;/strong&gt; O(V) to store the V-1 edges of the resulting Minimum Spanning Tree.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Combining these, the total space complexity is &lt;strong&gt;O(V + E)&lt;/strong&gt;. This makes it efficient in terms of memory usage, especially for sparse graphs where E is not excessively large.&lt;/p&gt;
&lt;h2 id="common-mistakes-and-how-to-avoid-them"&gt;Common Mistakes and How to Avoid Them&lt;/h2&gt;
&lt;p&gt;Implementing graph algorithms like Prim's can be tricky. Here are some common pitfalls and advice on how to avoid them:&lt;/p&gt;
&lt;h3 id="1-incorrect-priority-queue-management"&gt;1. Incorrect Priority Queue Management&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Using a max-heap instead of a min-heap, leading to a Maximum Spanning Tree (which is usually not what's desired).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Avoidance:&lt;/strong&gt; Always ensure your priority queue extracts the &lt;em&gt;minimum&lt;/em&gt; weight element. In C++, use &lt;code&gt;std::priority_queue&amp;lt;Edge, std::vector&amp;lt;Edge&amp;gt;, std::greater&amp;lt;Edge&amp;gt;&amp;gt;&lt;/code&gt;. In Python, &lt;code&gt;heapq&lt;/code&gt; is a min-heap by default. In Java, ensure your &lt;code&gt;Comparable&lt;/code&gt; implementation or &lt;code&gt;Comparator&lt;/code&gt; sorts in ascending order by weight.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Not correctly updating a vertex's key in the priority queue. If a vertex &lt;code&gt;v&lt;/code&gt; is already in the priority queue with a certain key, and a new, cheaper edge to &lt;code&gt;v&lt;/code&gt; is discovered, simply adding &lt;code&gt;v&lt;/code&gt; again can lead to redundant processing or even incorrect results if the algorithm processes an outdated, more expensive path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Avoidance:&lt;/strong&gt; The most common and simple way to handle this with a binary heap is to just add the new (better) entry to the priority queue. When extracting from the PQ, always perform a &lt;code&gt;visited&lt;/code&gt; check. If the vertex has already been &lt;code&gt;visited&lt;/code&gt;, simply skip it and continue to the next extraction. This implicitly ensures you always process the cheapest valid path to a vertex first.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-forgetting-to-mark-visited-nodes"&gt;2. Forgetting to Mark Visited Nodes&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Not marking vertices as &lt;code&gt;inMST&lt;/code&gt; (&lt;code&gt;visited&lt;/code&gt;) once they are added to the MST. This can lead to the algorithm re-processing edges to already included vertices, potentially forming cycles in the MST or resulting in an incorrect total weight due to redundant path consideration.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Avoidance:&lt;/strong&gt; As soon as a vertex &lt;code&gt;u&lt;/code&gt; is extracted from the priority queue and determined to be valid (i.e., &lt;code&gt;inMST[u]&lt;/code&gt; is false), mark &lt;code&gt;inMST[u] = true&lt;/code&gt; &lt;em&gt;before&lt;/em&gt; you iterate through its neighbors. This ensures that any subsequent attempts to add &lt;code&gt;u&lt;/code&gt; or use &lt;code&gt;u&lt;/code&gt; as a destination from an existing MST node are correctly filtered.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-incorrectly-updating-neighbor-weights"&gt;3. Incorrectly Updating Neighbor Weights&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Updating &lt;code&gt;key[v]&lt;/code&gt; for a neighbor &lt;code&gt;v&lt;/code&gt; only if &lt;code&gt;v&lt;/code&gt; is &lt;em&gt;not&lt;/em&gt; in the MST, but not also checking if the new edge weight is &lt;em&gt;smaller&lt;/em&gt; than the current &lt;code&gt;key[v]&lt;/code&gt;. If &lt;code&gt;key[v]&lt;/code&gt; already holds a cheaper path, updating it with a more expensive one is a critical error.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Avoidance:&lt;/strong&gt; The condition &lt;code&gt;!inMST[v] &amp;amp;&amp;amp; edgeWeight &amp;lt; key[v]&lt;/code&gt; is crucial. You only want to update &lt;code&gt;key[v]&lt;/code&gt; and add to the priority queue if the newly discovered edge from &lt;code&gt;u&lt;/code&gt; to &lt;code&gt;v&lt;/code&gt; offers a &lt;em&gt;better&lt;/em&gt; (cheaper) way to connect &lt;code&gt;v&lt;/code&gt; to the growing MST than any path found previously.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-handling-disconnected-graphs"&gt;4. Handling Disconnected Graphs&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Assuming Prim's will always produce a single spanning tree for any given graph.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Avoidance:&lt;/strong&gt; Prim's algorithm intrinsically works on connected components. If a graph is disconnected, running Prim's from one starting vertex will only find the MST of the connected component containing that vertex. To determine if the graph was fully connected, you can check if &lt;code&gt;len(visited) == len(graph)&lt;/code&gt; (in Python) or &lt;code&gt;edgesCount == numVertices - 1&lt;/code&gt; (in Java/C++) after the main loop finishes. If not, the result is an MST of a component, or a "minimum spanning forest" if you apply it iteratively to all components.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-off-by-one-errors-in-graph-representation"&gt;5. Off-by-One Errors in Graph Representation&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Incorrectly handling 0-indexed vs. 1-indexed vertices, which can lead to &lt;code&gt;IndexOutOfBounds&lt;/code&gt; errors or incorrect graph traversals.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Avoidance:&lt;/strong&gt; Be consistent with your vertex indexing throughout the problem. If your problem statement or dataset uses 1-indexed nodes, map them to 0-indexed internally for array/list access, or adjust array sizes accordingly to accommodate 1-based indexing.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="6-edge-case-graph-with-one-vertex"&gt;6. Edge Case: Graph with One Vertex&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Not explicitly considering a graph with a single vertex or an empty graph.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Avoidance:&lt;/strong&gt; A single-vertex graph has an MST with 0 cost and 0 edges, as it's already "connected." An empty graph also has 0 cost and 0 edges. Your code should handle these edge cases gracefully, usually by checking &lt;code&gt;numVertices == 0&lt;/code&gt; or &lt;code&gt;numVertices == 1&lt;/code&gt; at the beginning of your Prim's function.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;You've now taken a significant step in mastering graph algorithms by delving into the &lt;strong&gt;minimum spanning tree using Prim's algorithm in Python, Java, and C++&lt;/strong&gt;. We've covered the fundamental concepts of MSTs, the greedy approach behind Prim's algorithm, and provided detailed, step-by-step implementations across three major programming languages. Understanding Prim's algorithm is not just about writing code; it's about grasping an elegant solution to a pervasive problem in computer science and engineering.&lt;/p&gt;
&lt;p&gt;Prim's algorithm stands out for its efficiency, particularly with a priority queue, making it a go-to choice for scenarios like network design, circuit layout, and cluster analysis where finding the cheapest way to connect components is paramount. By internalizing its logic and practicing these implementations, you're well on your way to tackling more complex graph problems and building robust, optimized solutions. Keep practicing, experiment with different graph structures, and you'll find Prim's to be an invaluable tool in your algorithmic arsenal.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the primary difference between Prim's and Kruskal's algorithm for finding an MST?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Both Prim's and Kruskal's are greedy algorithms for finding an MST. Prim's algorithm starts from a single vertex and grows the MST by adding the cheapest edge connected to a vertex already in the MST. Kruskal's algorithm, on the other hand, considers all edges in increasing order of weight and adds an edge if it doesn't form a cycle with previously added edges, effectively building a "spanning forest" that eventually merges into a single MST.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: When should I choose Prim's algorithm over other MST algorithms?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Prim's algorithm is generally preferred for dense graphs (graphs with many edges relative to the number of vertices) when implemented with a binary heap, as its O(E log V) complexity can become O(V^2 log V) in dense cases, which is comparable to its O(V^2) adjacency matrix implementation. It's particularly efficient when you need to start building the MST from a specific source vertex, although the starting vertex doesn't affect the final MST.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Can Prim's algorithm be used on disconnected graphs?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: No, Prim's algorithm, by itself, is designed for connected graphs. If you run Prim's on a disconnected graph, it will find the Minimum Spanning Tree for the connected component that contains the arbitrary starting vertex. To find a Minimum Spanning Forest (a set of MSTs, one for each connected component) for a disconnected graph, you would need to run Prim's multiple times, starting from an unvisited vertex each time until all components are covered.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Wikipedia:&lt;/strong&gt; &lt;a href="https://en.wikipedia.org/wiki/Prim%27s_algorithm"&gt;Prim's algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;GeeksforGeeks:&lt;/strong&gt; &lt;a href="https://www.geeksforgeeks.org/prims-mst-for-adjacency-list-representation-greedy-algo-5/"&gt;Prim's Algorithm for Minimum Spanning Tree (MST)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;MIT OpenCourseware:&lt;/strong&gt; &lt;a href="https://ocw.mit.edu/courses/6-046j-design-and-analysis-of-algorithms-spring-2015/resources/lecture-15-minimum-spanning-trees-prims-and-kruskals/"&gt;Algorithms, Lecture 15: Minimum Spanning Trees, Prim's and Kruskal's&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;TopCoder Tutorials:&lt;/strong&gt; &lt;a href="https://www.topcoder.com/thrive/articles/Minimum%20Spanning%20Tree%20-%20Prim%27s%20Algorithm"&gt;Minimum Spanning Tree - Prim's Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Graph Theory"/><category term="Python"/><category term="Problem Solving"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/minimum-spanning-tree-prims-algorithm-python-java-cpp-hero.webp" width="1200"/><media:title type="plain">Minimum Spanning Tree with Prim's Algorithm: Python, Java &amp; C++</media:title><media:description type="plain">Master the minimum spanning tree using Prim's algorithm in Python, Java, and C++. This tutorial guides you through implementation, concepts, and optimization for efficient graph solutions.</media:description></entry><entry><title>Floyd Warshall Algorithm in Python, Java &amp; C++: A Tutorial</title><link href="https://analyticsdrive.tech/floyd-warshall-algorithm-python-java-cpp/" rel="alternate"/><published>2026-02-27T11:29:00+05:30</published><updated>2026-04-21T04:43:51.384451+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-27:/floyd-warshall-algorithm-python-java-cpp/</id><summary type="html">&lt;p&gt;Master the Floyd Warshall Algorithm in Python, Java, and C++ with this comprehensive tutorial. Learn to find all-pairs shortest paths efficiently.&lt;/p&gt;</summary><content type="html">&lt;h2 id="introduction-to-the-floyd-warshall-algorithm"&gt;Introduction to the Floyd Warshall Algorithm&lt;/h2&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#introduction-to-the-floyd-warshall-algorithm"&gt;Introduction to the Floyd Warshall Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-understanding-floyd-warshall"&gt;Prerequisites for Understanding Floyd Warshall&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#basic-graph-theory"&gt;Basic Graph Theory&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#dynamic-programming"&gt;Dynamic Programming&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#basic-programming-concepts"&gt;Basic Programming Concepts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-the-floyd-warshall-algorithm"&gt;Understanding the Floyd Warshall Algorithm&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-the-all-pairs-shortest-path-problem"&gt;What is the All-Pairs Shortest Path Problem?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#key-concepts"&gt;Key Concepts&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#dynamic-programming-paradigm"&gt;Dynamic Programming Paradigm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#intermediate-vertices"&gt;Intermediate Vertices&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#adjacency-matrix-representation"&gt;Adjacency Matrix Representation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-algorithms-core-logic"&gt;The Algorithm's Core Logic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#handling-negative-cycles"&gt;Handling Negative Cycles&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-the-floyd-warshall-algorithm-in-python-java-and-c"&gt;Implementing the Floyd Warshall Algorithm in Python, Java, and C++&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-1-initialize-the-distance-matrix"&gt;Step 1: Initialize the Distance Matrix&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-2-apply-the-triple-nested-loop"&gt;Step 2: Apply the Triple Nested Loop&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-3-check-for-negative-cycles-optional-but-recommended"&gt;Step 3: Check for Negative Cycles (Optional but Recommended)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-implementation"&gt;Python Implementation&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#explanation-for-python-implementation"&gt;Explanation for Python Implementation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#java-implementation"&gt;Java Implementation&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#explanation-for-java-implementation"&gt;Explanation for Java Implementation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#c-implementation"&gt;C++ Implementation&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#explanation-for-c-implementation"&gt;Explanation for C++ Implementation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity-ov3"&gt;Time Complexity: O(V³)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity-ov2"&gt;Space Complexity: O(V²)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#comparison-with-other-algorithms"&gt;Comparison with Other Algorithms&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-troubleshooting"&gt;Common Mistakes and Troubleshooting&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-incorrect-initialization-of-the-distance-matrix"&gt;1. Incorrect Initialization of the Distance Matrix&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-improper-handling-of-infinity"&gt;2. Improper Handling of "Infinity"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-incorrect-loop-order"&gt;3. Incorrect Loop Order&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-not-detecting-or-misinterpreting-negative-cycles"&gt;4. Not Detecting or Misinterpreting Negative Cycles&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-modifying-the-original-graph-adjacency-matrix"&gt;5. Modifying the Original Graph Adjacency Matrix&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6-off-by-one-errors-in-loop-bounds"&gt;6. Off-by-One Errors in Loop Bounds&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;p&gt;Welcome to this comprehensive tutorial where we will deeply explore the &lt;strong&gt;Floyd Warshall Algorithm in Python, Java and C++&lt;/strong&gt;. This powerful algorithm is a fundamental concept in graph theory, designed to find the shortest paths between all pairs of vertices in a weighted graph. Whether you're a student embarking on your algorithmic journey or a seasoned developer looking to refresh your knowledge, this tutorial will guide you through understanding its core principles, practical implementation, and common pitfalls across these popular programming languages. Mastering the Floyd Warshall Algorithm offers invaluable insights into dynamic programming and graph traversal, proving essential for various real-world applications ranging from network routing to transportation logistics. Our goal is to provide a clear, step-by-step approach, ensuring you can confidently apply this technique to your own projects.&lt;/p&gt;
&lt;h2 id="prerequisites-for-understanding-floyd-warshall"&gt;Prerequisites for Understanding Floyd Warshall&lt;/h2&gt;
&lt;p&gt;Before diving into the intricacies of the Floyd Warshall Algorithm, it’s beneficial to have a foundational understanding of several key computer science concepts. These prerequisites will ensure you can fully grasp the logic and implementation details presented in this tutorial.&lt;/p&gt;
&lt;h3 id="basic-graph-theory"&gt;Basic Graph Theory&lt;/h3&gt;
&lt;p&gt;Familiarity with fundamental graph theory concepts is essential. This includes knowing what a graph is (set of vertices and edges), understanding directed and undirected graphs, and being aware of weighted edges. Concepts like adjacency matrices, which represent connections and weights between nodes, are particularly important as they form the primary data structure for the Floyd Warshall Algorithm. Knowing the difference between an edge's weight (cost) and a path's total weight will also be helpful.&lt;/p&gt;
&lt;h3 id="dynamic-programming"&gt;Dynamic Programming&lt;/h3&gt;
&lt;p&gt;The Floyd Warshall Algorithm is a classic example of dynamic programming. A basic understanding of dynamic programming principles, such as breaking down a complex problem into smaller, overlapping subproblems and storing the results to avoid redundant calculations, will significantly aid your comprehension. If you've encountered problems like the Fibonacci sequence or knapsack problem using dynamic programming, you're well-prepared.&lt;/p&gt;
&lt;h3 id="basic-programming-concepts"&gt;Basic Programming Concepts&lt;/h3&gt;
&lt;p&gt;You should have a working knowledge of at least one of the target languages: Python, Java, or C++. This includes understanding:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Loops:&lt;/strong&gt; &lt;code&gt;for&lt;/code&gt; loops are extensively used in the algorithm's implementation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Arrays/Matrices:&lt;/strong&gt; Representing graphs using 2D arrays (adjacency matrices) is central to the algorithm.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Constants:&lt;/strong&gt; Using a large integer to represent "infinity" for unreachable paths.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Conditional Statements:&lt;/strong&gt; For comparisons and updates.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Possessing these foundational skills will enable you to follow the algorithmic logic and the provided code examples with ease, allowing you to focus on the unique aspects of the Floyd Warshall Algorithm itself.&lt;/p&gt;
&lt;h2 id="understanding-the-floyd-warshall-algorithm"&gt;Understanding the Floyd Warshall Algorithm&lt;/h2&gt;
&lt;p&gt;The Floyd Warshall Algorithm is an elegant and powerful algorithm for solving the all-pairs shortest path problem in a weighted, directed graph. Unlike single-source shortest path algorithms like &lt;a href="/dijkstra-algorithm-python-cpp-java-tutorial/"&gt;Dijkstra's Algorithm&lt;/a&gt; or the &lt;a href="/bellman-ford-algorithm-python-cpp-java-tutorial/"&gt;Bellman-Ford Algorithm&lt;/a&gt;, Floyd Warshall calculates the shortest path between every possible pair of vertices in the graph. It can handle graphs with positive and negative edge weights, but it cannot handle negative cycles (a cycle where the sum of edge weights is negative), as such a cycle would allow for infinitely decreasing path lengths.&lt;/p&gt;
&lt;h3 id="what-is-the-all-pairs-shortest-path-problem"&gt;What is the All-Pairs Shortest Path Problem?&lt;/h3&gt;
&lt;p&gt;The all-pairs shortest path problem asks us to find, for every pair of vertices (u, v) in a given graph, the path with the minimum total weight from u to v. This is a common problem in areas like network routing, where you need to know the fastest or cheapest way to get from any point to any other point.&lt;/p&gt;
&lt;h3 id="key-concepts"&gt;Key Concepts&lt;/h3&gt;
&lt;h4 id="dynamic-programming-paradigm"&gt;Dynamic Programming Paradigm&lt;/h4&gt;
&lt;p&gt;At its heart, the Floyd Warshall Algorithm is a prime example of dynamic programming. It builds up a solution incrementally. Instead of solving the problem directly, it solves a sequence of related subproblems, storing their solutions and reusing them to build the final answer. Each iteration improves upon the previous one by considering an additional vertex as a potential intermediate point on the shortest path.&lt;/p&gt;
&lt;h4 id="intermediate-vertices"&gt;Intermediate Vertices&lt;/h4&gt;
&lt;p&gt;The core idea revolves around iteratively allowing more and more vertices to be used as "intermediate" points in a path. Let &lt;code&gt;dist[i][j]&lt;/code&gt; be the shortest distance from vertex &lt;code&gt;i&lt;/code&gt; to vertex &lt;code&gt;j&lt;/code&gt;. When considering a vertex &lt;code&gt;k&lt;/code&gt; as an intermediate vertex, we ask: "Is the path from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;k&lt;/code&gt; then &lt;code&gt;k&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt; shorter than the current known shortest path from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt;?"&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Initially, &lt;code&gt;dist[i][j]&lt;/code&gt; is just the direct edge weight (or infinity if no direct edge).&lt;/li&gt;
&lt;li&gt;In the first iteration, we allow &lt;code&gt;V0&lt;/code&gt; as an intermediate vertex.&lt;/li&gt;
&lt;li&gt;In the second iteration, we allow &lt;code&gt;V0&lt;/code&gt; or &lt;code&gt;V1&lt;/code&gt; as intermediate vertices.&lt;/li&gt;
&lt;li&gt;This continues until we allow all vertices &lt;code&gt;V0&lt;/code&gt; through &lt;code&gt;V(N-1)&lt;/code&gt; as intermediate vertices.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="adjacency-matrix-representation"&gt;Adjacency Matrix Representation&lt;/h4&gt;
&lt;p&gt;The algorithm typically uses an adjacency matrix &lt;code&gt;dist[N][N]&lt;/code&gt; to store the shortest path distances.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dist[i][j]&lt;/code&gt; stores the shortest distance from vertex &lt;code&gt;i&lt;/code&gt; to vertex &lt;code&gt;j&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;i&lt;/code&gt; equals &lt;code&gt;j&lt;/code&gt;, &lt;code&gt;dist[i][j]&lt;/code&gt; is 0.&lt;/li&gt;
&lt;li&gt;If there is a direct edge from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt;, &lt;code&gt;dist[i][j]&lt;/code&gt; is its weight.&lt;/li&gt;
&lt;li&gt;If there is no direct edge, &lt;code&gt;dist[i][j]&lt;/code&gt; is initialized to infinity (a very large number).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="the-algorithms-core-logic"&gt;The Algorithm's Core Logic&lt;/h3&gt;
&lt;p&gt;The Floyd Warshall Algorithm proceeds in &lt;code&gt;N&lt;/code&gt; phases, where &lt;code&gt;N&lt;/code&gt; is the number of vertices in the graph. In the &lt;code&gt;k&lt;/code&gt;-th phase (where &lt;code&gt;k&lt;/code&gt; ranges from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;N-1&lt;/code&gt;), the algorithm considers paths that are allowed to use vertices &lt;code&gt;0, 1, ..., k&lt;/code&gt; as intermediate points.&lt;/p&gt;
&lt;p&gt;The core of the algorithm is a set of three nested loops:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;for k from 0 to N-1:         // k is the intermediate vertex
    for i from 0 to N-1:     // i is the source vertex
        for j from 0 to N-1: // j is the destination vertex
            // If vertex k is on the shortest path from i to j,
            // then update the value of dist[i][j]
            dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Let's break down this update rule:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dist[i][j]&lt;/code&gt; represents the current shortest path found from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt; without using any vertex greater than &lt;code&gt;k-1&lt;/code&gt; as an intermediate.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dist[i][k] + dist[k][j]&lt;/code&gt; represents the path from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt; that &lt;em&gt;does&lt;/em&gt; use &lt;code&gt;k&lt;/code&gt; as an intermediate vertex. Here, &lt;code&gt;dist[i][k]&lt;/code&gt; is the shortest path from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;k&lt;/code&gt; using intermediate vertices up to &lt;code&gt;k-1&lt;/code&gt;, and similarly for &lt;code&gt;dist[k][j]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;By taking the &lt;code&gt;min&lt;/code&gt; of these two values, we are effectively saying: the shortest path from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt; using intermediate vertices up to &lt;code&gt;k&lt;/code&gt; is either the shortest path without using &lt;code&gt;k&lt;/code&gt; (which is &lt;code&gt;dist[i][j]&lt;/code&gt;) or the shortest path that &lt;em&gt;does&lt;/em&gt; use &lt;code&gt;k&lt;/code&gt; (which is &lt;code&gt;dist[i][k] + dist[k][j]&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The crucial aspect of this algorithm's correctness is the order of the loops. The outermost loop &lt;em&gt;must&lt;/em&gt; iterate through &lt;code&gt;k&lt;/code&gt; (the intermediate vertex) first. This ensures that when &lt;code&gt;dist[i][k]&lt;/code&gt; and &lt;code&gt;dist[k][j]&lt;/code&gt; are used to update &lt;code&gt;dist[i][j]&lt;/code&gt;, they already contain the shortest path distances allowing intermediate vertices up to &lt;code&gt;k-1&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="handling-negative-cycles"&gt;Handling Negative Cycles&lt;/h3&gt;
&lt;p&gt;The Floyd Warshall Algorithm can also detect negative cycles. If, after the algorithm completes, &lt;code&gt;dist[i][i]&lt;/code&gt; for any vertex &lt;code&gt;i&lt;/code&gt; is negative, it indicates the presence of a negative cycle reachable from &lt;code&gt;i&lt;/code&gt; and returning to &lt;code&gt;i&lt;/code&gt;. This is because a negative cycle would allow the path length from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;i&lt;/code&gt; to continuously decrease.&lt;/p&gt;
&lt;h2 id="implementing-the-floyd-warshall-algorithm-in-python-java-and-c"&gt;Implementing the Floyd Warshall Algorithm in Python, Java, and C++&lt;/h2&gt;
&lt;p&gt;Now, let's proceed with the practical implementation of the Floyd Warshall Algorithm. We'll provide code examples in Python, Java, and C++, along with detailed explanations for each step.&lt;/p&gt;
&lt;h3 id="step-1-initialize-the-distance-matrix"&gt;Step 1: Initialize the Distance Matrix&lt;/h3&gt;
&lt;p&gt;The first step for all implementations is to set up an &lt;code&gt;N x N&lt;/code&gt; distance matrix. This matrix will initially represent the direct edge weights between vertices.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dist[i][j]&lt;/code&gt; will be the weight of the direct edge from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;i == j&lt;/code&gt;, &lt;code&gt;dist[i][j]&lt;/code&gt; is 0.&lt;/li&gt;
&lt;li&gt;If there's no direct edge from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt;, &lt;code&gt;dist[i][j]&lt;/code&gt; is set to a special "infinity" value to denote that the vertices are unreachable from each other (or that a path hasn't been found yet).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-2-apply-the-triple-nested-loop"&gt;Step 2: Apply the Triple Nested Loop&lt;/h3&gt;
&lt;p&gt;After initialization, the core of the algorithm involves three nested loops. The outermost loop iterates through all possible intermediate vertices (&lt;code&gt;k&lt;/code&gt;), followed by loops for source vertices (&lt;code&gt;i&lt;/code&gt;) and destination vertices (&lt;code&gt;j&lt;/code&gt;). Inside the innermost loop, the distance matrix is updated using the &lt;code&gt;min(dist[i][j], dist[i][k] + dist[k][j])&lt;/code&gt; formula.&lt;/p&gt;
&lt;h3 id="step-3-check-for-negative-cycles-optional-but-recommended"&gt;Step 3: Check for Negative Cycles (Optional but Recommended)&lt;/h3&gt;
&lt;p&gt;After the algorithm completes, you can iterate through the diagonal of the distance matrix (&lt;code&gt;dist[i][i]&lt;/code&gt;). If any &lt;code&gt;dist[i][i]&lt;/code&gt; is less than 0, it signifies the presence of a negative cycle in the graph.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id="python-implementation"&gt;Python Implementation&lt;/h3&gt;
&lt;p&gt;Here's how to implement the Floyd Warshall Algorithm using Python. Python's clear syntax and dynamic typing make it an excellent language for understanding algorithmic concepts.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;math&lt;/span&gt;

&lt;span class="c1"&gt;# Define a large number for infinity&lt;/span&gt;
&lt;span class="n"&gt;INF&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;inf&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;floyd_warshall_python&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;    Implements the Floyd Warshall Algorithm to find all-pairs shortest paths.&lt;/span&gt;

&lt;span class="sd"&gt;    Args:&lt;/span&gt;
&lt;span class="sd"&gt;        graph (list of lists): An adjacency matrix representation of the graph.&lt;/span&gt;
&lt;span class="sd"&gt;                               graph[i][j] is the weight of the edge from i to j.&lt;/span&gt;
&lt;span class="sd"&gt;                               If there is no direct edge, use INF. Self-loops are 0.&lt;/span&gt;

&lt;span class="sd"&gt;    Returns:&lt;/span&gt;
&lt;span class="sd"&gt;        list of lists: A matrix where dist[i][j] is the shortest path from i to j.&lt;/span&gt;
&lt;span class="sd"&gt;                       Returns None if a negative cycle is detected.&lt;/span&gt;
&lt;span class="sd"&gt;    &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="n"&gt;num_vertices&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Initialize the distance matrix&lt;/span&gt;
    &lt;span class="c1"&gt;# Make a deep copy to avoid modifying the original graph&lt;/span&gt;
    &lt;span class="n"&gt;dist&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[:]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="c1"&gt;# Main algorithm: Triple nested loops&lt;/span&gt;
    &lt;span class="c1"&gt;# k is the intermediate vertex&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num_vertices&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# i is the source vertex&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num_vertices&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="c1"&gt;# j is the destination vertex&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num_vertices&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="c1"&gt;# If vertex k is on the shortest path from i to j,&lt;/span&gt;
                &lt;span class="c1"&gt;# then update the value of dist[i][j]&lt;/span&gt;

                &lt;span class="c1"&gt;# Ensure that dist[i][k] and dist[k][j] are not INF&lt;/span&gt;
                &lt;span class="c1"&gt;# before adding to prevent overflow issues with INF + number&lt;/span&gt;
                &lt;span class="c1"&gt;# and to correctly handle unreachable paths.&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

    &lt;span class="c1"&gt;# Check for negative cycles&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num_vertices&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Negative cycle detected at vertex &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;!&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt; &lt;span class="c1"&gt;# Or handle as per requirement, e.g., raise an error&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;

&lt;span class="c1"&gt;# --- Example Usage (Python) ---&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="vm"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;__main__&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="c1"&gt;# Example graph represented as an adjacency matrix&lt;/span&gt;
    &lt;span class="c1"&gt;# 4 vertices: 0, 1, 2, 3&lt;/span&gt;
    &lt;span class="c1"&gt;# INF represents no direct edge&lt;/span&gt;

    &lt;span class="c1"&gt;# Graph 1: Basic example&lt;/span&gt;
    &lt;span class="n"&gt;graph1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;--- Graph 1: Basic Example ---&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;shortest_paths1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;floyd_warshall_python&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;shortest_paths1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Shortest path matrix:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;shortest_paths1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;INF&amp;quot;&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Graph 2: Example with negative edge weights (but no negative cycle)&lt;/span&gt;
    &lt;span class="n"&gt;graph2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;--- Graph 2: With Negative Edges (No Negative Cycle) ---&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;shortest_paths2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;floyd_warshall_python&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;shortest_paths2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Shortest path matrix:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;shortest_paths2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;INF&amp;quot;&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Graph 3: Example with a negative cycle&lt;/span&gt;
    &lt;span class="n"&gt;graph3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="c1"&gt;# Cycle: 0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0 (1 + (-3) + (-2) = -4)&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;--- Graph 3: With Negative Cycle ---&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;shortest_paths3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;floyd_warshall_python&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;shortest_paths3&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Shortest path matrix:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;shortest_paths3&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;INF&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;INF&amp;quot;&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h4 id="explanation-for-python-implementation"&gt;Explanation for Python Implementation&lt;/h4&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;INF = float('inf')&lt;/code&gt;&lt;/strong&gt;: We use &lt;code&gt;float('inf')&lt;/code&gt; from Python's math module to represent unreachable paths. This is a convenient way to handle the concept of "infinity" in numerical comparisons.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;floyd_warshall_python(graph)&lt;/code&gt; function&lt;/strong&gt;:&lt;ul&gt;
&lt;li&gt;Takes an adjacency matrix &lt;code&gt;graph&lt;/code&gt; as input.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;num_vertices = len(graph)&lt;/code&gt;: Determines the number of vertices.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dist = [row[:] for row in graph]&lt;/code&gt;: Creates a deep copy of the input graph to prevent modifying the original matrix. This &lt;code&gt;dist&lt;/code&gt; matrix will store the shortest paths.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Triple Nested Loops&lt;/strong&gt;: The heart of the algorithm.&lt;ul&gt;
&lt;li&gt;The outer loop &lt;code&gt;for k in range(num_vertices)&lt;/code&gt; iterates through all possible intermediate vertices.&lt;/li&gt;
&lt;li&gt;The middle loop &lt;code&gt;for i in range(num_vertices)&lt;/code&gt; iterates through all possible source vertices.&lt;/li&gt;
&lt;li&gt;The inner loop &lt;code&gt;for j in range(num_vertices)&lt;/code&gt; iterates through all possible destination vertices.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Update Rule&lt;/strong&gt;: &lt;code&gt;dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])&lt;/code&gt;. Before adding, we check &lt;code&gt;if dist[i][k] != INF and dist[k][j] != INF&lt;/code&gt;. This check is crucial to prevent &lt;code&gt;INF + actual_number&lt;/code&gt; from resulting in &lt;code&gt;INF&lt;/code&gt; and potentially allowing a path through an unreachable node to appear shorter than it is. It correctly handles cases where a direct path from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;k&lt;/code&gt; or &lt;code&gt;k&lt;/code&gt; to &lt;code&gt;j&lt;/code&gt; does not exist.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Negative Cycle Detection&lt;/strong&gt;: After the loops, we check if &lt;code&gt;dist[i][i] &amp;lt; 0&lt;/code&gt; for any &lt;code&gt;i&lt;/code&gt;. If true, a negative cycle exists, and the function returns &lt;code&gt;None&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Finally, the function returns the &lt;code&gt;dist&lt;/code&gt; matrix containing all-pairs shortest paths.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Example Usage&lt;/strong&gt;: Demonstrates how to call the function with sample graphs, including one with a negative cycle to show the detection mechanism.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h3 id="java-implementation"&gt;Java Implementation&lt;/h3&gt;
&lt;p&gt;For Java, we'll use a similar structure, adapting to Java's strong typing and array handling.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.Arrays&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;FloydWarshallJava&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Define a large number for infinity. Integer.MAX_VALUE / 2 is safer than MAX_VALUE&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// to prevent overflow when adding two &amp;quot;infinity&amp;quot; values.&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;final&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1_000_000_000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// A sufficiently large number&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;floydWarshall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Initialize the distance matrix&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Main algorithm: Triple nested loops&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// k is the intermediate vertex&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// i is the source vertex&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// j is the destination vertex&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// If vertex k is on the shortest path from i to j,&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// then update the value of dist[i][j]&lt;/span&gt;

&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// Ensure that dist[i][k] and dist[k][j] are not INF&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// before adding to prevent overflow&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                        &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Check for negative cycles&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;][&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Negative cycle detected at vertex &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;!&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Or throw an exception&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Helper method to print the matrix&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;printMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;No valid shortest path matrix (negative cycle detected).&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;INF\t&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;\t&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// --- Example Usage (Java) ---&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Example graph represented as an adjacency matrix&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// 4 vertices: 0, 1, 2, 3&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// INF represents no direct edge&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Graph 1: Basic example&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;--- Graph 1: Basic Example ---&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shortestPaths1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;floydWarshall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;printMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shortestPaths1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Graph 2: Example with negative edge weights (but no negative cycle)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;--- Graph 2: With Negative Edges (No Negative Cycle) ---&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shortestPaths2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;floydWarshall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;printMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shortestPaths2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Graph 3: Example with a negative cycle&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Cycle: 0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0 (1 + (-3) + (-2) = -4)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;--- Graph 3: With Negative Cycle ---&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[][]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shortestPaths3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;floydWarshall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;printMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shortestPaths3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;    &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;h4 id="explanation-for-java-implementation"&gt;Explanation for Java Implementation&lt;/h4&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;INF = 1_000_000_000&lt;/code&gt;&lt;/strong&gt;: We use a large integer value to represent infinity. Using &lt;code&gt;Integer.MAX_VALUE&lt;/code&gt; directly can cause issues if &lt;code&gt;Integer.MAX_VALUE + X&lt;/code&gt; is performed, leading to an overflow and becoming a negative number. A sufficiently large number, roughly &lt;code&gt;MAX_VALUE / 2&lt;/code&gt;, is a common practice to avoid this.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;floydWarshall(int[][] graph)&lt;/code&gt; function&lt;/strong&gt;:&lt;ul&gt;
&lt;li&gt;Takes a 2D integer array &lt;code&gt;graph&lt;/code&gt; (adjacency matrix) as input.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;int[][] dist = new int[numVertices][numVertices];&lt;/code&gt;: Declares and initializes the &lt;code&gt;dist&lt;/code&gt; matrix. Java arrays are initialized to default values (0 for &lt;code&gt;int&lt;/code&gt;), so explicit copying from &lt;code&gt;graph&lt;/code&gt; is necessary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Initialization Loop&lt;/strong&gt;: Explicitly copies values from the input &lt;code&gt;graph&lt;/code&gt; to &lt;code&gt;dist&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Triple Nested Loops&lt;/strong&gt;: Identical logic to the Python version, using &lt;code&gt;Math.min()&lt;/code&gt; for comparison.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Overflow Prevention&lt;/strong&gt;: The condition &lt;code&gt;dist[i][k] != INF &amp;amp;&amp;amp; dist[k][j] != INF&lt;/code&gt; is crucial in Java (and C++) to prevent integer overflow when adding &lt;code&gt;INF&lt;/code&gt; values, which could result in a negative number and incorrect path detection.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Negative Cycle Detection&lt;/strong&gt;: Similar logic, checking &lt;code&gt;dist[i][i] &amp;lt; 0&lt;/code&gt;. Returns &lt;code&gt;null&lt;/code&gt; if detected.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;printMatrix&lt;/code&gt; helper method&lt;/strong&gt;: A utility method to print the 2D array, handling the &lt;code&gt;INF&lt;/code&gt; representation for better readability.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;main&lt;/code&gt; method&lt;/strong&gt;: Provides example usage with different graphs.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h3 id="c-implementation"&gt;C++ Implementation&lt;/h3&gt;
&lt;p&gt;The C++ implementation will be very similar to Java, utilizing &lt;code&gt;std::vector&lt;/code&gt; for dynamic arrays and &lt;code&gt;INT_MAX&lt;/code&gt; for infinity, with careful consideration for potential integer overflow.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;algorithm&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // For std::min&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;limits&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt;    // For std::numeric_limits&lt;/span&gt;

&lt;span class="c1"&gt;// Define a large number for infinity.&lt;/span&gt;
&lt;span class="c1"&gt;// Using a value less than INT_MAX to avoid overflow when adding.&lt;/span&gt;
&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;numeric_limits&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;::&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;

&lt;span class="c1"&gt;// Function to implement Floyd Warshall Algorithm&lt;/span&gt;
&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;floydWarshall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Initialize the distance matrix&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Main algorithm: Triple nested loops&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// k is the intermediate vertex&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// i is the source vertex&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// j is the destination vertex&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// If vertex k is on the shortest path from i to j,&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// then update the value of dist[i][j]&lt;/span&gt;

&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// Ensure that dist[i][k] and dist[k][j] are not INF&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// before adding to prevent overflow issues and incorrect comparisons.&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Check for negative cycles&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Negative cycle detected at vertex &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;!&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// A common way to signal an invalid state, e.g., by returning an empty matrix&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// or a matrix filled with INF/specific error codes.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// For simplicity, we&amp;#39;ll return a special value.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{};&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Return an empty vector of vectors to indicate error&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Helper function to print the matrix&lt;/span&gt;
&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;printMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;No valid shortest path matrix (negative cycle detected).&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;INF&lt;/span&gt;&lt;span class="se"&gt;\t&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\t&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// --- Example Usage (C++) ---&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example graph represented as an adjacency matrix&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// 4 vertices: 0, 1, 2, 3&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// INF represents no direct edge&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Graph 1: Basic example&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;--- Graph 1: Basic Example ---&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shortestPaths1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;floydWarshall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;printMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shortestPaths1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Graph 2: Example with negative edge weights (but no negative cycle)&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;-4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;--- Graph 2: With Negative Edges (No Negative Cycle) ---&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shortestPaths2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;floydWarshall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;printMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shortestPaths2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Graph 3: Example with a negative cycle&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;graph3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-3&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;-2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;INF&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Cycle: 0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0 (1 + (-3) + (-2) = -4)&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;--- Graph 3: With Negative Cycle ---&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shortestPaths3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;floydWarshall&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;printMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shortestPaths3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&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;h4 id="explanation-for-c-implementation"&gt;Explanation for C++ Implementation&lt;/h4&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;#include &amp;lt;limits&amp;gt;&lt;/code&gt; and &lt;code&gt;INF&lt;/code&gt;&lt;/strong&gt;: We use &lt;code&gt;std::numeric_limits&amp;lt;int&amp;gt;::max() / 2&lt;/code&gt; for &lt;code&gt;INF&lt;/code&gt;. This is a robust way to get the maximum integer value and then halve it to prevent overflow issues when adding two &lt;code&gt;INF&lt;/code&gt; or &lt;code&gt;INF + a_number&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;std::vector&amp;lt;std::vector&amp;lt;int&amp;gt;&amp;gt;&lt;/code&gt;&lt;/strong&gt;: C++ uses &lt;code&gt;std::vector&lt;/code&gt; for dynamic arrays, making it flexible for graph representation.&lt;ul&gt;
&lt;li&gt;&lt;code&gt;std::vector&amp;lt;std::vector&amp;lt;int&amp;gt;&amp;gt; dist(numVertices, std::vector&amp;lt;int&amp;gt;(numVertices));&lt;/code&gt; initializes an &lt;code&gt;N x N&lt;/code&gt; matrix.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Initialization and Loops&lt;/strong&gt;: The logic for initializing &lt;code&gt;dist&lt;/code&gt; and the three nested loops are functionally identical to the Java implementation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Overflow Prevention&lt;/strong&gt;: The &lt;code&gt;if (dist[i][k] != INF &amp;amp;&amp;amp; dist[k][j] != INF)&lt;/code&gt; check is equally critical in C++ for &lt;code&gt;int&lt;/code&gt; types to prevent overflow.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Negative Cycle Detection&lt;/strong&gt;: Similar detection, returning an empty &lt;code&gt;std::vector&amp;lt;std::vector&amp;lt;int&amp;gt;&amp;gt;&lt;/code&gt; to signify an error or invalid state due to a negative cycle.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;printMatrix&lt;/code&gt;&lt;/strong&gt;: A helper function to display the matrix, with &lt;code&gt;const auto&amp;amp;&lt;/code&gt; for efficient iteration and &lt;code&gt;const&lt;/code&gt; reference for the matrix to avoid unnecessary copying.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the performance characteristics of an algorithm is just as important as knowing how to implement it. The Floyd Warshall Algorithm has a distinct time and space complexity profile that makes it suitable for certain types of problems and graph sizes.&lt;/p&gt;
&lt;h3 id="time-complexity-ov3"&gt;Time Complexity: O(V³)&lt;/h3&gt;
&lt;p&gt;The time complexity of the Floyd Warshall Algorithm is cubic, specifically &lt;strong&gt;O(V³)&lt;/strong&gt;, where &lt;code&gt;V&lt;/code&gt; is the number of vertices in the graph. This arises directly from its structure:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The algorithm consists of three perfectly nested &lt;code&gt;for&lt;/code&gt; loops.&lt;/li&gt;
&lt;li&gt;Each loop iterates &lt;code&gt;V&lt;/code&gt; times (once for each vertex).&lt;/li&gt;
&lt;li&gt;The innermost operation (the &lt;code&gt;min&lt;/code&gt; comparison and addition) takes constant time.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Therefore, the total number of operations is proportional to &lt;code&gt;V * V * V&lt;/code&gt;, leading to &lt;code&gt;O(V³)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This cubic complexity implies that the algorithm's performance degrades rapidly as the number of vertices increases. For graphs with a very large number of vertices (e.g., thousands), &lt;code&gt;O(V³)&lt;/code&gt; can become computationally prohibitive. For instance, a graph with 1000 vertices would require approximately 1 billion operations, which could take a significant amount of time.&lt;/p&gt;
&lt;h3 id="space-complexity-ov2"&gt;Space Complexity: O(V²)&lt;/h3&gt;
&lt;p&gt;The space complexity of the Floyd Warshall Algorithm is quadratic, specifically &lt;strong&gt;O(V²)&lt;/strong&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The algorithm primarily uses a 2D array (the distance matrix &lt;code&gt;dist&lt;/code&gt;) of size &lt;code&gt;V x V&lt;/code&gt; to store the shortest path distances between all pairs of vertices.&lt;/li&gt;
&lt;li&gt;This matrix directly scales with the square of the number of vertices.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;No other auxiliary data structures that grow significantly with &lt;code&gt;V&lt;/code&gt; are typically required. Therefore, the total space required is dominated by this &lt;code&gt;V x V&lt;/code&gt; matrix.&lt;/p&gt;
&lt;h3 id="comparison-with-other-algorithms"&gt;Comparison with Other Algorithms&lt;/h3&gt;
&lt;p&gt;It's useful to put these complexities into perspective with other shortest path algorithms:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href="/dijkstra-algorithm-python-cpp-java-tutorial/"&gt;Dijkstra's Algorithm&lt;/a&gt;&lt;/strong&gt;: For single-source shortest paths on graphs with non-negative edge weights. Using a min-priority queue, its complexity is typically &lt;code&gt;O(E log V)&lt;/code&gt; or &lt;code&gt;O(E + V log V)&lt;/code&gt;, where &lt;code&gt;E&lt;/code&gt; is the number of edges. If run &lt;code&gt;V&lt;/code&gt; times (once for each source) to solve the all-pairs problem, it becomes &lt;code&gt;O(V * E log V)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href="/bellman-ford-algorithm-python-cpp-java-tutorial/"&gt;Bellman-Ford Algorithm&lt;/a&gt;&lt;/strong&gt;: For single-source shortest paths on graphs with negative edge weights (but no negative cycles). Its complexity is &lt;code&gt;O(V * E)&lt;/code&gt;. If run &lt;code&gt;V&lt;/code&gt; times, it becomes &lt;code&gt;O(V² * E)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Key Takeaways on Complexity:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Floyd Warshall is simpler to implement than &lt;code&gt;V&lt;/code&gt; runs of Dijkstra or Bellman-Ford for the all-pairs problem, especially when path reconstruction is not explicitly handled in those &lt;code&gt;V&lt;/code&gt; runs.&lt;/li&gt;
&lt;li&gt;For dense graphs (where &lt;code&gt;E&lt;/code&gt; approaches &lt;code&gt;V²&lt;/code&gt;), &lt;code&gt;V&lt;/code&gt; runs of Dijkstra or Bellman-Ford can approach or exceed &lt;code&gt;O(V³)&lt;/code&gt;. In such cases, Floyd Warshall is competitive.&lt;/li&gt;
&lt;li&gt;For sparse graphs (where &lt;code&gt;E&lt;/code&gt; is much smaller than &lt;code&gt;V²&lt;/code&gt;), &lt;code&gt;V&lt;/code&gt; runs of Dijkstra (&lt;code&gt;O(V E log V)&lt;/code&gt;) can be significantly faster than Floyd Warshall's &lt;code&gt;O(V³)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The Floyd Warshall Algorithm's ability to handle negative edge weights (unlike Dijkstra) and its clean detection of negative cycles are significant advantages in its specific use cases.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In essence, the &lt;code&gt;O(V³)&lt;/code&gt; time complexity makes Floyd Warshall best suited for graphs where the number of vertices &lt;code&gt;V&lt;/code&gt; is relatively small, typically up to a few hundred. For larger graphs, alternative approaches or more specialized algorithms might be necessary, depending on the graph's density and edge weight properties.&lt;/p&gt;
&lt;h2 id="common-mistakes-and-troubleshooting"&gt;Common Mistakes and Troubleshooting&lt;/h2&gt;
&lt;p&gt;Implementing graph algorithms like the &lt;strong&gt;Floyd Warshall Algorithm in Python, Java and C++&lt;/strong&gt; can introduce several common pitfalls. Being aware of these will help you troubleshoot and write more robust code.&lt;/p&gt;
&lt;h3 id="1-incorrect-initialization-of-the-distance-matrix"&gt;1. Incorrect Initialization of the Distance Matrix&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Not setting diagonal elements &lt;code&gt;dist[i][i]&lt;/code&gt; to 0 (shortest path from a vertex to itself is 0). Or, incorrectly using &lt;code&gt;0&lt;/code&gt; for non-existent edges, which implies a free path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resolution&lt;/strong&gt;: Always initialize &lt;code&gt;dist[i][i]&lt;/code&gt; to 0 for all &lt;code&gt;i&lt;/code&gt;. For non-existent direct edges &lt;code&gt;(i, j)&lt;/code&gt;, initialize &lt;code&gt;dist[i][j]&lt;/code&gt; to your &lt;code&gt;INF&lt;/code&gt; constant (a very large number). Only direct edges with given weights should populate the initial &lt;code&gt;dist[i][j]&lt;/code&gt; value. Ensure your graph representation correctly differentiates between an edge with weight 0 and no edge at all.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-improper-handling-of-infinity"&gt;2. Improper Handling of "Infinity"&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Using &lt;code&gt;Integer.MAX_VALUE&lt;/code&gt; directly for &lt;code&gt;INF&lt;/code&gt; in Java/C++ without consideration for overflow. If &lt;code&gt;INF + any_number&lt;/code&gt; results in a value exceeding &lt;code&gt;MAX_VALUE&lt;/code&gt;, it will wrap around to a negative number, leading to incorrect shortest path calculations (e.g., an unreachable path suddenly appearing as a very short negative path).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resolution&lt;/strong&gt;: In languages like Java and C++, use &lt;code&gt;Integer.MAX_VALUE / 2&lt;/code&gt; or a sufficiently large constant less than &lt;code&gt;MAX_VALUE&lt;/code&gt; for &lt;code&gt;INF&lt;/code&gt;. In Python, &lt;code&gt;float('inf')&lt;/code&gt; handles this gracefully, but be cautious if mixing with large integers that might exceed standard &lt;code&gt;int&lt;/code&gt; limits in certain contexts (though generally not an issue for typical graph sizes). Always check &lt;code&gt;if dist[i][k] != INF &amp;amp;&amp;amp; dist[k][j] != INF&lt;/code&gt; before attempting &lt;code&gt;dist[i][k] + dist[k][j]&lt;/code&gt; to prevent adding &lt;code&gt;INF&lt;/code&gt; values, which might also result in &lt;code&gt;INF&lt;/code&gt;, but could mask specific numerical issues or comparisons.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-incorrect-loop-order"&gt;3. Incorrect Loop Order&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Swapping the order of the &lt;code&gt;k&lt;/code&gt;, &lt;code&gt;i&lt;/code&gt;, and &lt;code&gt;j&lt;/code&gt; loops. The algorithm's correctness hinges on &lt;code&gt;k&lt;/code&gt; (the intermediate vertex) being the outermost loop.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resolution&lt;/strong&gt;: The order &lt;strong&gt;must&lt;/strong&gt; be &lt;code&gt;for k&lt;/code&gt;, then &lt;code&gt;for i&lt;/code&gt;, then &lt;code&gt;for j&lt;/code&gt;. The &lt;code&gt;k&lt;/code&gt; loop iteratively allows more vertices to be used as intermediate points, and its completion ensures that &lt;code&gt;dist[i][k]&lt;/code&gt; and &lt;code&gt;dist[k][j]&lt;/code&gt; are already updated to their shortest possible values considering intermediate vertices up to &lt;code&gt;k-1&lt;/code&gt; before they are used to update &lt;code&gt;dist[i][j]&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-not-detecting-or-misinterpreting-negative-cycles"&gt;4. Not Detecting or Misinterpreting Negative Cycles&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Failing to check for negative cycles or misinterpreting their presence. If a negative cycle exists and is reachable, the concept of a "shortest path" becomes ill-defined as one could traverse the cycle indefinitely to achieve arbitrarily small (large negative) path weights.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resolution&lt;/strong&gt;: After the main triple loops complete, iterate through &lt;code&gt;dist[i][i]&lt;/code&gt; for all &lt;code&gt;i&lt;/code&gt;. If any &lt;code&gt;dist[i][i] &amp;lt; 0&lt;/code&gt;, a negative cycle is detected. The algorithm effectively finds the shortest path even with negative cycles, but if &lt;code&gt;dist[i][i]&lt;/code&gt; is negative, it indicates an issue for paths involving &lt;code&gt;i&lt;/code&gt;. Your function should ideally return a special value (e.g., &lt;code&gt;null&lt;/code&gt; in Java, empty vector in C++, &lt;code&gt;None&lt;/code&gt; in Python) or throw an exception when a negative cycle is detected, as the computed shortest paths might no longer be meaningful.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-modifying-the-original-graph-adjacency-matrix"&gt;5. Modifying the Original Graph Adjacency Matrix&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Directly modifying the input &lt;code&gt;graph&lt;/code&gt; matrix instead of working on a copy. This can lead to unexpected side effects if the original graph is needed elsewhere.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resolution&lt;/strong&gt;: Always create a deep copy of the initial adjacency matrix into your &lt;code&gt;dist&lt;/code&gt; matrix. In Python, &lt;code&gt;dist = [row[:] for row in graph]&lt;/code&gt; creates a deep copy for a list of lists. In Java/C++, explicitly copy elements or ensure your &lt;code&gt;dist&lt;/code&gt; matrix is a separate, new allocation.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="6-off-by-one-errors-in-loop-bounds"&gt;6. Off-by-One Errors in Loop Bounds&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Incorrectly setting loop bounds (e.g., &lt;code&gt;range(num_vertices - 1)&lt;/code&gt; instead of &lt;code&gt;range(num_vertices)&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resolution&lt;/strong&gt;: Ensure all loops iterate correctly from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;num_vertices - 1&lt;/code&gt; (inclusive of &lt;code&gt;0&lt;/code&gt;, exclusive of &lt;code&gt;num_vertices&lt;/code&gt; in Python's &lt;code&gt;range&lt;/code&gt;, or inclusive of both in C++/Java &lt;code&gt;for&lt;/code&gt; loops).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;By keeping these common issues in mind, you can approach the implementation of the Floyd Warshall Algorithm with greater confidence and build more robust and accurate solutions.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;We've journeyed through the intricacies of the &lt;strong&gt;Floyd Warshall Algorithm in Python, Java and C++&lt;/strong&gt;, a foundational tool in graph theory for solving the all-pairs shortest path problem. This tutorial has equipped you with a comprehensive understanding of its dynamic programming principles, the core logic involving intermediate vertices, and practical, step-by-step implementations in Python, Java, and C++. We covered the essential initialization of the distance matrix, the critical triple nested loop structure, and even the important mechanism for detecting negative cycles.&lt;/p&gt;
&lt;p&gt;You now understand that while its &lt;code&gt;O(V³)&lt;/code&gt; time complexity limits its application to graphs with a relatively small number of vertices, its elegance, simplicity, and ability to handle negative edge weights (unlike Dijkstra's) make it invaluable in scenarios where finding all-pairs shortest paths is crucial. We also explored common pitfalls, such as incorrect initialization, issues with "infinity" representation, and the vital order of loops, providing you with the knowledge to troubleshoot effectively.&lt;/p&gt;
&lt;p&gt;The Floyd Warshall Algorithm is more than just a theoretical concept; it's a powerful and practical technique with applications spanning network routing, resource allocation, and even social network analysis. By mastering this algorithm, you've not only added a significant tool to your algorithmic arsenal but also deepened your understanding of dynamic programming and graph traversal. Continue to practice with different graph structures and experiment with its parameters to solidify your grasp on this essential algorithm.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the main purpose of the Floyd Warshall Algorithm?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The Floyd Warshall Algorithm is designed to find the shortest paths between all possible pairs of vertices in a weighted graph. It calculates the minimum total weight to travel from any starting vertex to any other destination vertex.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Can Floyd Warshall handle negative edge weights, and what about negative cycles?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Yes, the Floyd Warshall Algorithm can correctly handle graphs with negative edge weights. However, it cannot correctly find shortest paths in graphs that contain negative cycles, as such cycles would allow for infinitely decreasing path lengths. The algorithm can detect the presence of negative cycles.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: How does the Floyd Warshall Algorithm compare to Dijkstra's Algorithm?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Floyd Warshall finds all-pairs shortest paths and can handle negative edge weights, with a time complexity of &lt;code&gt;O(V³)&lt;/code&gt; (where V is the number of vertices). Dijkstra's Algorithm, conversely, finds single-source shortest paths, requires non-negative edge weights, and typically has a complexity of &lt;code&gt;O(E log V)&lt;/code&gt; or &lt;code&gt;O(E + V log V)&lt;/code&gt; (where E is the number of edges). For dense graphs, Floyd Warshall can be competitive for the all-pairs problem.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Wikipedia - Floyd–Warshall algorithm:&lt;/strong&gt; &lt;a href="https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm"&gt;https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;GeeksforGeeks - Floyd Warshall Algorithm:&lt;/strong&gt; &lt;a href="https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/"&gt;https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Programiz - Floyd Warshall Algorithm:&lt;/strong&gt; &lt;a href="https://www.programiz.com/dsa/floyd-warshall-algorithm"&gt;https://www.programiz.com/dsa/floyd-warshall-algorithm&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Dynamic Programming"/><category term="Python"/><category term="Problem Solving"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/floyd-warshall-algorithm-python-java-cpp-hero.webp" width="1200"/><media:title type="plain">Floyd Warshall Algorithm in Python, Java &amp; C++: A Tutorial</media:title><media:description type="plain">Master the Floyd Warshall Algorithm in Python, Java, and C++ with this comprehensive tutorial. Learn to find all-pairs shortest paths efficiently.</media:description></entry><entry><title>Bellman Ford Algorithm in Python, C++, Java: A Complete Tutorial</title><link href="https://analyticsdrive.tech/bellman-ford-algorithm-python-cpp-java-tutorial/" rel="alternate"/><published>2026-02-27T09:45:00+05:30</published><updated>2026-04-21T04:43:51.286296+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-27:/bellman-ford-algorithm-python-cpp-java-tutorial/</id><summary type="html">&lt;p&gt;Master the Bellman Ford Algorithm in Python, C++, and Java. This comprehensive tutorial covers implementation, time complexity, and handling negative cycles.&lt;/p&gt;</summary><content type="html">&lt;p&gt;The Bellman Ford Algorithm in Python, C++, Java is a fundamental and incredibly powerful algorithm for finding the shortest paths from a single source vertex to all other vertices in a weighted digraph. Unlike &lt;a href="/dijkstra-algorithm-python-cpp-java-tutorial/"&gt;Dijkstra's algorithm&lt;/a&gt;, Bellman Ford possesses the crucial ability to handle graphs containing edges with negative weights, a scenario where Dijkstra's falls short. This makes it an indispensable tool in various computational problems, especially in network routing and arbitrage detection. This &lt;strong&gt;complete tutorial&lt;/strong&gt; will guide you through its mechanics, explain its underlying principles, and provide practical implementations in &lt;strong&gt;Python, C++, and Java&lt;/strong&gt;. By the end, you'll have a robust understanding of how to apply this algorithm, detect negative cycles, and appreciate its significance in graph theory.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-understanding-bellman-ford"&gt;Prerequisites for Understanding Bellman Ford&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-the-bellman-ford-algorithm"&gt;Understanding the Bellman Ford Algorithm&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-the-bellman-ford-algorithm"&gt;What is the Bellman Ford Algorithm?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-intuition-behind-relaxation"&gt;The Intuition Behind Relaxation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#why-bellman-ford-is-important-vs-dijkstras"&gt;Why Bellman Ford is Important (vs. Dijkstra's)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#dealing-with-negative-cycles"&gt;Dealing with Negative Cycles&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#steps-to-implement-the-bellman-ford-algorithm"&gt;Steps to Implement the Bellman Ford Algorithm&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-1-initialize-distances"&gt;Step 1: Initialize Distances&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-2-relax-edges-v-1-times"&gt;Step 2: Relax Edges V-1 Times&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-3-detect-negative-cycles"&gt;Step 3: Detect Negative Cycles&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-the-bellman-ford-algorithm-in-python-c-and-java"&gt;Implementing the Bellman Ford Algorithm in Python, C++, and Java&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#implementation-in-python"&gt;Implementation in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementation-in-c"&gt;Implementation in C++&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementation-in-java"&gt;Implementation in Java&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#bellman-ford-algorithm-trace-example"&gt;Bellman Ford Algorithm Trace Example&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#iteration-1-k-0"&gt;Iteration 1 (k = 0):&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#iteration-2-k-1"&gt;Iteration 2 (k = 1):&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#iteration-3-k-2"&gt;Iteration 3 (k = 2):&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#iteration-4-k-3"&gt;Iteration 4 (k = 3):&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#negative-cycle-check-iteration-v-5"&gt;Negative Cycle Check (Iteration V = 5):&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-troubleshooting"&gt;Common Mistakes and Troubleshooting&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#bellman-ford-vs-dijkstras-algorithm"&gt;Bellman Ford vs. Dijkstra's Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#applications-of-bellman-ford"&gt;Applications of Bellman Ford&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="prerequisites-for-understanding-bellman-ford"&gt;Prerequisites for Understanding Bellman Ford&lt;/h2&gt;
&lt;p&gt;Before diving deep into the Bellman Ford algorithm, it's beneficial to have a foundational understanding of a few key concepts. Familiarity with these topics will significantly enhance your learning experience and make the complex aspects of the algorithm more intuitive.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Graph Theory Basics:&lt;/strong&gt; A solid grasp of what graphs are, including vertices (nodes), edges, directed vs. undirected graphs, and weighted graphs. Understanding how graphs are typically represented (adjacency matrix or adjacency list) is also crucial. For a deeper dive into common graph problems, you might explore challenges like the &lt;a href="/cses-labyrinth-problem-python-java-cpp-guide/"&gt;CSES Labyrinth Problem&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Basic Data Structures:&lt;/strong&gt; Knowledge of arrays, lists, and potentially hash maps/dictionaries will be helpful for implementing the algorithm in different programming languages.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Algorithm Analysis:&lt;/strong&gt; An understanding of time and space complexity (Big O notation) will allow you to appreciate the performance characteristics of Bellman Ford.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Shortest Path Problem:&lt;/strong&gt; A general understanding of what the shortest path problem entails and why it's important. For another approach to finding shortest distances in a specific type of grid, consider how algorithms like BFS and DP are used in the &lt;a href="/01-matrix-problem-shortest-distance-bfs-dp-explained/"&gt;01 Matrix Problem&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="understanding-the-bellman-ford-algorithm"&gt;Understanding the Bellman Ford Algorithm&lt;/h2&gt;
&lt;p&gt;The Bellman Ford algorithm is a single-source shortest path algorithm capable of handling graphs where edge weights can be negative. This distinguishes it from Dijkstra's algorithm, which only works with non-negative edge weights. The core idea behind Bellman Ford is a technique called "relaxation," repeatedly updating estimated distances to vertices until the shortest path is found.&lt;/p&gt;
&lt;h3 id="what-is-the-bellman-ford-algorithm"&gt;What is the Bellman Ford Algorithm?&lt;/h3&gt;
&lt;p&gt;At its heart, Bellman Ford is an iterative algorithm that progressively finds shorter paths. It operates on the principle that if there are &lt;code&gt;V&lt;/code&gt; vertices in a graph, the shortest path between any two vertices can have at most &lt;code&gt;V-1&lt;/code&gt; edges. This fact is critical because it tells us exactly how many iterations we need to perform. For each iteration, the algorithm considers every edge in the graph and attempts to relax it.&lt;/p&gt;
&lt;h3 id="the-intuition-behind-relaxation"&gt;The Intuition Behind Relaxation&lt;/h3&gt;
&lt;p&gt;Relaxation is the process of updating the shortest path estimate to a vertex if a shorter path is found. Imagine you're trying to find the quickest way from your starting point (source) to various destinations. Initially, you might assume all destinations are infinitely far away, except your starting point, which is 0 distance from itself.&lt;/p&gt;
&lt;p&gt;When you traverse an edge from vertex &lt;code&gt;u&lt;/code&gt; to vertex &lt;code&gt;v&lt;/code&gt; with weight &lt;code&gt;w(u, v)&lt;/code&gt;, you check if the current shortest path distance to &lt;code&gt;u&lt;/code&gt; plus the weight of the edge &lt;code&gt;(u, v)&lt;/code&gt; is less than the current shortest path distance to &lt;code&gt;v&lt;/code&gt;. If it is, it means you've found a shorter path to &lt;code&gt;v&lt;/code&gt; via &lt;code&gt;u&lt;/code&gt;, so you update &lt;code&gt;v&lt;/code&gt;'s distance. This process is repeated for all edges in the graph.&lt;/p&gt;
&lt;p&gt;The algorithm performs &lt;code&gt;V-1&lt;/code&gt; such iterations. Why &lt;code&gt;V-1&lt;/code&gt;? Because in a simple path (no repeated vertices), the maximum number of edges between any two vertices in a graph with &lt;code&gt;V&lt;/code&gt; vertices is &lt;code&gt;V-1&lt;/code&gt;. Each iteration guarantees that shortest paths with one more edge are correctly evaluated. After &lt;code&gt;V-1&lt;/code&gt; iterations, all shortest paths (assuming no negative cycles reachable from the source) will have been found.&lt;/p&gt;
&lt;h3 id="why-bellman-ford-is-important-vs-dijkstras"&gt;Why Bellman Ford is Important (vs. Dijkstra's)&lt;/h3&gt;
&lt;p&gt;The primary reason for Bellman Ford's importance is its ability to handle negative edge weights. In real-world scenarios, "weight" might not always represent a positive cost or distance. For example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Financial Arbitrage:&lt;/strong&gt; In currency exchange, an edge weight could represent the logarithm of the exchange rate, and negative weights would indicate a profitable exchange path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Network Routing:&lt;/strong&gt; In some network topologies, certain links might have negative "costs" representing a performance gain or a preferred route.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resource Optimization:&lt;/strong&gt; A negative weight could signify a "gain" rather than a "cost" in a resource allocation problem.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Dijkstra's algorithm relies on a greedy approach that assumes once a vertex is visited and its shortest path finalized, that path won't change. This assumption breaks down with negative edge weights, as a later, unvisited negative edge could potentially offer a shorter path to an already "finalized" vertex. Bellman Ford, with its iterative relaxation, avoids this pitfall by continually re-evaluating paths.&lt;/p&gt;
&lt;h3 id="dealing-with-negative-cycles"&gt;Dealing with Negative Cycles&lt;/h3&gt;
&lt;p&gt;One of the most powerful features of the Bellman Ford algorithm is its capacity to detect negative cycles. A negative cycle is a cycle in the graph where the sum of the edge weights along the cycle is negative. If a negative cycle is reachable from the source vertex, then the shortest path to any vertex on that cycle (or reachable from it) becomes undefined, or technically, approaches negative infinity, because you could traverse the cycle indefinitely to reduce the path cost.&lt;/p&gt;
&lt;p&gt;After &lt;code&gt;V-1&lt;/code&gt; iterations, if we can still relax any edge &lt;code&gt;(u, v)&lt;/code&gt; (i.e., &lt;code&gt;dist[u] + weight(u, v) &amp;lt; dist[v]&lt;/code&gt;), it indicates the presence of a negative cycle. This is because if there were no negative cycles, all shortest paths would have been finalized within &lt;code&gt;V-1&lt;/code&gt; iterations. Any further relaxation implies that paths can still be made shorter, which is only possible if traversing a negative cycle repeatedly. This detection mechanism is crucial for many applications where negative cycles signify impossible or undesirable conditions (like infinite profit in arbitrage).&lt;/p&gt;
&lt;h2 id="steps-to-implement-the-bellman-ford-algorithm"&gt;Steps to Implement the Bellman Ford Algorithm&lt;/h2&gt;
&lt;p&gt;Implementing the Bellman Ford algorithm involves three main phases: initialization, repeated relaxation of all edges, and finally, a check for negative cycles. Let's break down each step in detail.&lt;/p&gt;
&lt;h3 id="step-1-initialize-distances"&gt;Step 1: Initialize Distances&lt;/h3&gt;
&lt;p&gt;The first step in any shortest path algorithm is to set up the initial conditions for path distances.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Create a Distance Array:&lt;/strong&gt; Initialize an array &lt;code&gt;dist&lt;/code&gt; of size &lt;code&gt;V&lt;/code&gt; (number of vertices). This array will store the shortest distance from the source vertex to every other vertex.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Set Source Distance:&lt;/strong&gt; Set &lt;code&gt;dist[source]&lt;/code&gt; to &lt;code&gt;0&lt;/code&gt;. The distance from the source to itself is always zero.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Set Other Distances to Infinity:&lt;/strong&gt; For all other vertices &lt;code&gt;i&lt;/code&gt; (where &lt;code&gt;i != source&lt;/code&gt;), set &lt;code&gt;dist[i]&lt;/code&gt; to &lt;code&gt;infinity&lt;/code&gt;. This &lt;code&gt;infinity&lt;/code&gt; represents an unreachable or extremely large distance, indicating that we haven't yet found a path to these vertices. In practical implementations, &lt;code&gt;infinity&lt;/code&gt; is usually a very large integer (e.g., &lt;code&gt;sys.maxsize&lt;/code&gt; in Python, &lt;code&gt;INT_MAX&lt;/code&gt; in C++, &lt;code&gt;Integer.MAX_VALUE&lt;/code&gt; in Java).&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="step-2-relax-edges-v-1-times"&gt;Step 2: Relax Edges V-1 Times&lt;/h3&gt;
&lt;p&gt;This is the core iterative process where the algorithm refines the shortest path estimates.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Outer Loop:&lt;/strong&gt; Run an outer loop &lt;code&gt;V-1&lt;/code&gt; times. Each iteration of this loop represents considering paths with one additional edge.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Inner Loop (Edge Traversal):&lt;/strong&gt; Inside the outer loop, iterate through &lt;em&gt;all&lt;/em&gt; edges &lt;code&gt;(u, v)&lt;/code&gt; in the graph. For each edge, perform the relaxation operation:&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Check for Shorter Path:&lt;/strong&gt; If &lt;code&gt;dist[u]&lt;/code&gt; is not &lt;code&gt;infinity&lt;/code&gt; (meaning &lt;code&gt;u&lt;/code&gt; is reachable from the source) AND &lt;code&gt;dist[u] + weight(u, v) &amp;lt; dist[v]&lt;/code&gt;, then a shorter path to &lt;code&gt;v&lt;/code&gt; through &lt;code&gt;u&lt;/code&gt; has been found.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Update Distance:&lt;/strong&gt; Update &lt;code&gt;dist[v] = dist[u] + weight(u, v)&lt;/code&gt;. This effectively "relaxes" the edge &lt;code&gt;(u, v)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;After &lt;code&gt;V-1&lt;/code&gt; iterations, if the graph contains no negative cycles reachable from the source, the &lt;code&gt;dist&lt;/code&gt; array will hold the shortest path distances from the source to all other reachable vertices.&lt;/p&gt;
&lt;h3 id="step-3-detect-negative-cycles"&gt;Step 3: Detect Negative Cycles&lt;/h3&gt;
&lt;p&gt;The final step is crucial for verifying the validity of the computed shortest paths and identifying problematic graph structures.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;One More Iteration:&lt;/strong&gt; After the &lt;code&gt;V-1&lt;/code&gt; relaxation passes are complete, run one &lt;em&gt;additional&lt;/em&gt; iteration over all edges.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Check for Further Relaxation:&lt;/strong&gt; For each edge &lt;code&gt;(u, v)&lt;/code&gt; in the graph, check if &lt;code&gt;dist[u]&lt;/code&gt; is not &lt;code&gt;infinity&lt;/code&gt; AND &lt;code&gt;dist[u] + weight(u, v) &amp;lt; dist[v]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Negative Cycle Indication:&lt;/strong&gt; If this condition is true for &lt;em&gt;any&lt;/em&gt; edge, it means that a path can still be shortened after &lt;code&gt;V-1&lt;/code&gt; iterations. This conclusively indicates the presence of a negative cycle reachable from the source vertex. In this case, shortest paths are not well-defined, and the algorithm should report the presence of a negative cycle.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Shortest Paths Validated:&lt;/strong&gt; If no edge can be relaxed in this &lt;code&gt;V&lt;/code&gt;-th iteration, it means the graph does not contain any negative cycles reachable from the source, and the &lt;code&gt;dist&lt;/code&gt; array contains the correct shortest path distances.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="implementing-the-bellman-ford-algorithm-in-python-c-and-java"&gt;Implementing the Bellman Ford Algorithm in Python, C++, and Java&lt;/h2&gt;
&lt;p&gt;Let's illustrate the Bellman Ford algorithm with code examples. We'll use a sample graph to demonstrate the process:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Graph Representation:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;Vertices: 0, 1, 2, 3, 4
Edges:
(0, 1, -1)
(0, 2, 4)
(1, 2, 3)
(1, 3, 2)
(1, 4, 2)
(3, 2, 5)
(3, 1, 1)
(4, 3, -3)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Source vertex: 0&lt;/p&gt;
&lt;h3 id="implementation-in-python"&gt;Implementation in Python&lt;/h3&gt;
&lt;p&gt;Python's dynamic typing and list comprehensions make graph representation and algorithm implementation quite concise. We'll represent the graph as a list of edges, where each edge is a tuple &lt;code&gt;(u, v, weight)&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;sys&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Graph&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;vertices&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;vertices&lt;/span&gt; &lt;span class="c1"&gt;# Number of vertices&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt; &lt;span class="c1"&gt;# List of edges. Each edge is (u, v, weight)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;bellman_ford&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;src&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="c1"&gt;# Step 1: Initialize distances from src to all other vertices as INFINITE&lt;/span&gt;
        &lt;span class="c1"&gt;# and distance to src as 0&lt;/span&gt;
        &lt;span class="n"&gt;dist&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;maxsize&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;
        &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;src&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 2: Relax all edges V-1 times&lt;/span&gt;
        &lt;span class="c1"&gt;# A shortest path from src to any other vertex can have at most V-1 edges&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;maxsize&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                    &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 3: Check for negative cycles&lt;/span&gt;
        &lt;span class="c1"&gt;# If we can still relax an edge, then there&amp;#39;s a negative cycle&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;maxsize&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Graph contains negative weight cycle!&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="c1"&gt;# Shortest paths are not well-defined&lt;/span&gt;

        &lt;span class="c1"&gt;# Print the shortest distances if no negative cycle&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;print_solution&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;print_solution&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Vertex Distance from Source&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;maxsize&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="se"&gt;\t&lt;/span&gt;&lt;span class="s2"&gt; unreachable&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="se"&gt;\t&lt;/span&gt;&lt;span class="s2"&gt; &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Example Usage&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="vm"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;__main__&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Bellman Ford Algorithm in Python:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;bellman_ford&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Example with a negative cycle:&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;Graph with a negative cycle:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g_cycle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# This creates a negative cycle 0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0 (sum = -1)&lt;/span&gt;
    &lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;bellman_ford&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Python Code Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;Graph&lt;/code&gt; class in Python stores the number of vertices (&lt;code&gt;self.V&lt;/code&gt;) and a list of edges (&lt;code&gt;self.graph&lt;/code&gt;). Each edge is a tuple &lt;code&gt;(u, v, w)&lt;/code&gt; representing a directed edge from &lt;code&gt;u&lt;/code&gt; to &lt;code&gt;v&lt;/code&gt; with weight &lt;code&gt;w&lt;/code&gt;. The &lt;code&gt;add_edge&lt;/code&gt; method simply appends these tuples to the &lt;code&gt;self.graph&lt;/code&gt; list.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;bellman_ford(self, src)&lt;/code&gt; method implements the algorithm:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; &lt;code&gt;dist&lt;/code&gt; array is created, filled with &lt;code&gt;sys.maxsize&lt;/code&gt; (Python's representation of infinity), and &lt;code&gt;dist[src]&lt;/code&gt; is set to 0.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Relaxation:&lt;/strong&gt; Two nested loops are used. The outer loop runs &lt;code&gt;self.V - 1&lt;/code&gt; times. The inner loop iterates through all edges in &lt;code&gt;self.graph&lt;/code&gt;. Inside the inner loop, the relaxation condition &lt;code&gt;dist[u] != sys.maxsize and dist[u] + w &amp;lt; dist[v]&lt;/code&gt; is checked. If true, &lt;code&gt;dist[v]&lt;/code&gt; is updated. The &lt;code&gt;dist[u] != sys.maxsize&lt;/code&gt; check prevents arithmetic overflow if &lt;code&gt;dist[u]&lt;/code&gt; is still infinity, ensuring that we only consider paths from reachable vertices.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Negative Cycle Detection:&lt;/strong&gt; After &lt;code&gt;V-1&lt;/code&gt; iterations, a final pass over all edges is made. If any edge can still be relaxed, it signifies a negative cycle, and a message is printed, and the function returns. Otherwise, the shortest distances are valid and printed using &lt;code&gt;print_solution&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="implementation-in-c"&gt;Implementation in C++&lt;/h3&gt;
&lt;p&gt;In C++, we can use a &lt;code&gt;std::vector&lt;/code&gt; to store the edges and an array/vector for distances. We'll define a &lt;code&gt;struct&lt;/code&gt; for edges for better readability.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;limits&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // For std::numeric_limits&lt;/span&gt;

&lt;span class="c1"&gt;// Define a structure for an edge&lt;/span&gt;
&lt;span class="k"&gt;struct&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Graph&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Number of vertices&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// List of edges&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;vertices&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vertices&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;bellmanFord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;src&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 1: Initialize distances from src to all other vertices as INFINITE&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// and distance to src as 0&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;numeric_limits&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;::&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;src&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 2: Relax all edges V-1 times&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// A shortest path from src to any other vertex can have at most V-1 edges&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// Check if dist[u] is not infinity to prevent overflow when adding weight&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;numeric_limits&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;::&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 3: Check for negative cycles&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If we can still relax an edge, then there&amp;#39;s a negative cycle&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;numeric_limits&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;::&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Graph contains negative weight cycle!&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Shortest paths are not well-defined&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Print the shortest distances if no negative cycle&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;printSolution&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;printSolution&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Vertex Distance from Source&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;numeric_limits&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;::&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\t&lt;/span&gt;&lt;span class="s"&gt; unreachable&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\t&lt;/span&gt;&lt;span class="s"&gt; &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;// Example Usage&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Bellman Ford Algorithm in C++:&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;bellmanFord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example with a negative cycle:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;Graph with a negative cycle:&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add_edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// This creates a negative cycle 0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0 (sum = -1)&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;bellmanFord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&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;&lt;strong&gt;C++ Code Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Similar to the Python version, the &lt;code&gt;Graph&lt;/code&gt; class in C++ stores the number of vertices &lt;code&gt;V&lt;/code&gt; and a &lt;code&gt;std::vector&lt;/code&gt; of &lt;code&gt;Edge&lt;/code&gt; structs. The &lt;code&gt;Edge&lt;/code&gt; struct holds &lt;code&gt;u&lt;/code&gt;, &lt;code&gt;v&lt;/code&gt;, and &lt;code&gt;weight&lt;/code&gt;. &lt;code&gt;add_edge&lt;/code&gt; pushes these &lt;code&gt;Edge&lt;/code&gt; objects into the vector.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;bellmanFord(int src)&lt;/code&gt; method:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; A &lt;code&gt;std::vector&amp;lt;long long&amp;gt; dist&lt;/code&gt; is created and initialized with &lt;code&gt;std::numeric_limits&amp;lt;long long&amp;gt;::max()&lt;/code&gt; for infinity. Using &lt;code&gt;long long&lt;/code&gt; for distances is a good practice to prevent overflow, especially when dealing with potentially large sums of negative edge weights. &lt;code&gt;dist[src]&lt;/code&gt; is set to 0.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Relaxation:&lt;/strong&gt; The outer loop iterates &lt;code&gt;V - 1&lt;/code&gt; times. The inner loop uses a range-based for loop to iterate through all &lt;code&gt;Edge&lt;/code&gt; objects in the &lt;code&gt;edges&lt;/code&gt; vector. The relaxation logic is identical to Python.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Negative Cycle Detection:&lt;/strong&gt; A final loop checks for any further relaxation. If found, a negative cycle message is printed, and the function returns. Otherwise, &lt;code&gt;printSolution&lt;/code&gt; displays the results.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="implementation-in-java"&gt;Implementation in Java&lt;/h3&gt;
&lt;p&gt;Java's approach will be similar to C++, using an &lt;code&gt;ArrayList&lt;/code&gt; to store &lt;code&gt;Edge&lt;/code&gt; objects and an array for distances.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.ArrayList&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.Arrays&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Define a class for an edge&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Graph&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Number of vertices&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// List of edges&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;vertices&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;vertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;bellmanFord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;src&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 1: Initialize distances from src to all other vertices as INFINITE&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// and distance to src as 0&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Use long to prevent overflow&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;fill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;MAX_VALUE&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;src&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 2: Relax all edges V-1 times&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// A shortest path from src to any other vertex can have at most V-1 edges&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;u&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;v&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// Check if dist[u] is not infinity to prevent overflow when adding weight&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="c1"&gt;// and to only consider reachable nodes for relaxation&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;MAX_VALUE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 3: Check for negative cycles&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If we can still relax an edge, then there&amp;#39;s a negative cycle&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;u&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;v&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;MAX_VALUE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Graph contains negative weight cycle!&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Shortest paths are not well-defined&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Print the shortest distances if no negative cycle&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;printSolution&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;printSolution&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Vertex Distance from Source&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;V&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;MAX_VALUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;\t unreachable&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;\t &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Example Usage&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BellmanFord&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Bellman Ford Algorithm in Java:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;bellmanFord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Example with a negative cycle:&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;\nGraph with a negative cycle:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Graph&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addEdge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// This creates a negative cycle 0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0 (sum = -1)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;g_cycle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;bellmanFord&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &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;&lt;strong&gt;Java Code Explanation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The Java implementation mirrors the C++ version very closely.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Edge&lt;/code&gt; Class:&lt;/strong&gt; A dedicated &lt;code&gt;Edge&lt;/code&gt; class encapsulates &lt;code&gt;u&lt;/code&gt;, &lt;code&gt;v&lt;/code&gt;, and &lt;code&gt;weight&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Graph&lt;/code&gt; Class:&lt;/strong&gt; Stores &lt;code&gt;V&lt;/code&gt; and an &lt;code&gt;ArrayList&amp;lt;Edge&amp;gt; edges&lt;/code&gt;. &lt;code&gt;addEdge&lt;/code&gt; adds new &lt;code&gt;Edge&lt;/code&gt; objects.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;bellmanFord(int src)&lt;/code&gt;:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; &lt;code&gt;long[] dist&lt;/code&gt; array is used, initialized with &lt;code&gt;Long.MAX_VALUE&lt;/code&gt; for infinity, and &lt;code&gt;dist[src]&lt;/code&gt; is set to 0. Using &lt;code&gt;long&lt;/code&gt; is critical for avoiding integer overflow with potentially large path sums.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Relaxation:&lt;/strong&gt; The outer loop runs &lt;code&gt;V - 1&lt;/code&gt; times. The inner loop iterates through the &lt;code&gt;edges&lt;/code&gt; &lt;code&gt;ArrayList&lt;/code&gt;. The relaxation logic is identical, including the check &lt;code&gt;dist[u] != Long.MAX_VALUE&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Negative Cycle Detection:&lt;/strong&gt; A final loop checks for negative cycles. If detected, a message is printed and the method returns. Otherwise, &lt;code&gt;printSolution&lt;/code&gt; displays the results.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;All three implementations demonstrate the same core logic, adapting to the specific syntax and standard libraries of each language.&lt;/p&gt;
&lt;h2 id="bellman-ford-algorithm-trace-example"&gt;Bellman Ford Algorithm Trace Example&lt;/h2&gt;
&lt;p&gt;To truly understand how Bellman Ford works, let's trace its execution on our example graph with 5 vertices (0, 1, 2, 3, 4) and source vertex 0.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Graph Edges:&lt;/strong&gt; (u, v, weight)
(0, 1, -1), (0, 2, 4), (1, 2, 3), (1, 3, 2), (1, 4, 2), (3, 2, 5), (3, 1, 1), (4, 3, -3)&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Initial Distances (src=0):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;dist = [0, INF, INF, INF, INF]&lt;/code&gt; (where INF = &lt;code&gt;sys.maxsize&lt;/code&gt;/&lt;code&gt;Long.MAX_VALUE&lt;/code&gt;)&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Vertices (V) = 5. We need &lt;code&gt;V-1 = 4&lt;/code&gt; iterations.&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id="iteration-1-k-0"&gt;Iteration 1 (k = 0):&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Initial &lt;code&gt;dist&lt;/code&gt; for this iteration:&lt;/strong&gt; &lt;code&gt;[0, INF, INF, INF, INF]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edges (u, v, w):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;(0, 1, -1): &lt;code&gt;dist[0]&lt;/code&gt; (0) + (-1) = -1 &amp;lt; &lt;code&gt;dist[1]&lt;/code&gt; (INF). Relax. &lt;code&gt;dist[1] = -1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;(0, 2, 4): &lt;code&gt;dist[0]&lt;/code&gt; (0) + 4 = 4 &amp;lt; &lt;code&gt;dist[2]&lt;/code&gt; (INF). Relax. &lt;code&gt;dist[2] = 4&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;(1, 2, 3): &lt;code&gt;dist[1]&lt;/code&gt; (-1) + 3 = 2 &amp;lt; &lt;code&gt;dist[2]&lt;/code&gt; (4). Relax. &lt;code&gt;dist[2] = 2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;(1, 3, 2): &lt;code&gt;dist[1]&lt;/code&gt; (-1) + 2 = 1 &amp;lt; &lt;code&gt;dist[3]&lt;/code&gt; (INF). Relax. &lt;code&gt;dist[3] = 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;(1, 4, 2): &lt;code&gt;dist[1]&lt;/code&gt; (-1) + 2 = 1 &amp;lt; &lt;code&gt;dist[4]&lt;/code&gt; (INF). Relax. &lt;code&gt;dist[4] = 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;(3, 2, 5): &lt;code&gt;dist[3]&lt;/code&gt; (1) + 5 = 6. Not less than &lt;code&gt;dist[2]&lt;/code&gt; (2). No relaxation.&lt;/li&gt;
&lt;li&gt;(3, 1, 1): &lt;code&gt;dist[3]&lt;/code&gt; (1) + 1 = 2. Not less than &lt;code&gt;dist[1]&lt;/code&gt; (-1). No relaxation.&lt;/li&gt;
&lt;li&gt;(4, 3, -3): &lt;code&gt;dist[4]&lt;/code&gt; (1) + (-3) = -2. Not less than &lt;code&gt;dist[3]&lt;/code&gt; (1). No relaxation.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;dist&lt;/code&gt; after Iteration 1:&lt;/strong&gt; &lt;code&gt;[0, -1, 2, 1, 1]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id="iteration-2-k-1"&gt;Iteration 2 (k = 1):&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Initial &lt;code&gt;dist&lt;/code&gt; for this iteration:&lt;/strong&gt; &lt;code&gt;[0, -1, 2, 1, 1]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edges (u, v, w):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;(0, 1, -1): &lt;code&gt;dist[0]&lt;/code&gt; (0) + (-1) = -1. Not less than &lt;code&gt;dist[1]&lt;/code&gt; (-1). No relaxation.&lt;/li&gt;
&lt;li&gt;(0, 2, 4): &lt;code&gt;dist[0]&lt;/code&gt; (0) + 4 = 4. Not less than &lt;code&gt;dist[2]&lt;/code&gt; (2). No relaxation.&lt;/li&gt;
&lt;li&gt;(1, 2, 3): &lt;code&gt;dist[1]&lt;/code&gt; (-1) + 3 = 2. Not less than &lt;code&gt;dist[2]&lt;/code&gt; (2). No relaxation.&lt;/li&gt;
&lt;li&gt;(1, 3, 2): &lt;code&gt;dist[1]&lt;/code&gt; (-1) + 2 = 1. Not less than &lt;code&gt;dist[3]&lt;/code&gt; (1). No relaxation.&lt;/li&gt;
&lt;li&gt;(1, 4, 2): &lt;code&gt;dist[1]&lt;/code&gt; (-1) + 2 = 1. Not less than &lt;code&gt;dist[4]&lt;/code&gt; (1). No relaxation.&lt;/li&gt;
&lt;li&gt;(3, 2, 5): &lt;code&gt;dist[3]&lt;/code&gt; (1) + 5 = 6. Not less than &lt;code&gt;dist[2]&lt;/code&gt; (2). No relaxation.&lt;/li&gt;
&lt;li&gt;(3, 1, 1): &lt;code&gt;dist[3]&lt;/code&gt; (1) + 1 = 2. Not less than &lt;code&gt;dist[1]&lt;/code&gt; (-1). No relaxation.&lt;/li&gt;
&lt;li&gt;(4, 3, -3): &lt;code&gt;dist[4]&lt;/code&gt; (1) + (-3) = -2 &amp;lt; &lt;code&gt;dist[3]&lt;/code&gt; (1). Relax. &lt;code&gt;dist[3] = -2&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;dist&lt;/code&gt; after Iteration 2:&lt;/strong&gt; &lt;code&gt;[0, -1, 2, -2, 1]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id="iteration-3-k-2"&gt;Iteration 3 (k = 2):&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Initial &lt;code&gt;dist&lt;/code&gt; for this iteration:&lt;/strong&gt; &lt;code&gt;[0, -1, 2, -2, 1]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edges (u, v, w):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;... (edges 0,1,2,3,4 relaxations similar to previous, no changes yet due to &lt;code&gt;dist[3]&lt;/code&gt; update) ...&lt;/li&gt;
&lt;li&gt;(3, 2, 5): &lt;code&gt;dist[3]&lt;/code&gt; (-2) + 5 = 3. Not less than &lt;code&gt;dist[2]&lt;/code&gt; (2). No relaxation.&lt;/li&gt;
&lt;li&gt;(3, 1, 1): &lt;code&gt;dist[3]&lt;/code&gt; (-2) + 1 = -1. Not less than &lt;code&gt;dist[1]&lt;/code&gt; (-1). No relaxation.&lt;/li&gt;
&lt;li&gt;(4, 3, -3): &lt;code&gt;dist[4]&lt;/code&gt; (1) + (-3) = -2. Not less than &lt;code&gt;dist[3]&lt;/code&gt; (-2). No relaxation.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;dist&lt;/code&gt; after Iteration 3:&lt;/strong&gt; &lt;code&gt;[0, -1, 2, -2, 1]&lt;/code&gt; (No changes from previous iteration, all paths of length up to 3 edges have been settled)&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id="iteration-4-k-3"&gt;Iteration 4 (k = 3):&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Initial &lt;code&gt;dist&lt;/code&gt; for this iteration:&lt;/strong&gt; &lt;code&gt;[0, -1, 2, -2, 1]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;In this iteration, no edge relaxation will occur, as all shortest paths (up to 4 edges) have been found.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;dist&lt;/code&gt; after Iteration 4:&lt;/strong&gt; &lt;code&gt;[0, -1, 2, -2, 1]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id="negative-cycle-check-iteration-v-5"&gt;Negative Cycle Check (Iteration V = 5):&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Final &lt;code&gt;dist&lt;/code&gt; before check:&lt;/strong&gt; &lt;code&gt;[0, -1, 2, -2, 1]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edges (u, v, w):&lt;/strong&gt; We iterate through all edges one last time.&lt;ul&gt;
&lt;li&gt;For (0,1,-1): &lt;code&gt;dist[0]&lt;/code&gt; (0) + (-1) = -1. &lt;code&gt;dist[1]&lt;/code&gt; is -1. No change.&lt;/li&gt;
&lt;li&gt;For (0,2,4): &lt;code&gt;dist[0]&lt;/code&gt; (0) + 4 = 4. &lt;code&gt;dist[2]&lt;/code&gt; is 2. No change.&lt;/li&gt;
&lt;li&gt;For (1,2,3): &lt;code&gt;dist[1]&lt;/code&gt; (-1) + 3 = 2. &lt;code&gt;dist[2]&lt;/code&gt; is 2. No change.&lt;/li&gt;
&lt;li&gt;For (1,3,2): &lt;code&gt;dist[1]&lt;/code&gt; (-1) + 2 = 1. &lt;code&gt;dist[3]&lt;/code&gt; is -2. No change (1 is not less than -2).&lt;/li&gt;
&lt;li&gt;For (1,4,2): &lt;code&gt;dist[1]&lt;/code&gt; (-1) + 2 = 1. &lt;code&gt;dist[4]&lt;/code&gt; is 1. No change.&lt;/li&gt;
&lt;li&gt;For (3,2,5): &lt;code&gt;dist[3]&lt;/code&gt; (-2) + 5 = 3. &lt;code&gt;dist[2]&lt;/code&gt; is 2. No change (3 is not less than 2).&lt;/li&gt;
&lt;li&gt;For (3,1,1): &lt;code&gt;dist[3]&lt;/code&gt; (-2) + 1 = -1. &lt;code&gt;dist[1]&lt;/code&gt; is -1. No change.&lt;/li&gt;
&lt;li&gt;For (4,3,-3): &lt;code&gt;dist[4]&lt;/code&gt; (1) + (-3) = -2. &lt;code&gt;dist[3]&lt;/code&gt; is -2. No change.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Since no &lt;code&gt;dist[v]&lt;/code&gt; was updated in this final pass, there is no negative cycle reachable from the source.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Final Shortest Distances from Source 0:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;To 0: 0&lt;/li&gt;
&lt;li&gt;To 1: -1 (Path: 0 -&amp;gt; 1)&lt;/li&gt;
&lt;li&gt;To 2: 2 (Path: 0 -&amp;gt; 1 -&amp;gt; 2)&lt;/li&gt;
&lt;li&gt;To 3: -2 (Path: 0 -&amp;gt; 1 -&amp;gt; 4 -&amp;gt; 3)&lt;/li&gt;
&lt;li&gt;To 4: 1 (Path: 0 -&amp;gt; 1 -&amp;gt; 4)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This trace vividly demonstrates how the algorithm iteratively refines the shortest path estimates, eventually converging to the correct values, even with negative edge weights.&lt;/p&gt;
&lt;h2 id="time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the performance characteristics of an algorithm is crucial for choosing the right tool for a given problem.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;The time complexity of the Bellman Ford algorithm is dominated by its two main loops:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Outer Loop:&lt;/strong&gt; This loop runs &lt;code&gt;V-1&lt;/code&gt; times (or &lt;code&gt;V&lt;/code&gt; times if you include the negative cycle check pass, though it's typically accounted for separately or as part of the &lt;code&gt;V-1&lt;/code&gt; passes followed by one final check). &lt;code&gt;V&lt;/code&gt; is the number of vertices.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Inner Loop:&lt;/strong&gt; Inside each iteration of the outer loop, the algorithm iterates through &lt;em&gt;all&lt;/em&gt; edges in the graph. If &lt;code&gt;E&lt;/code&gt; is the number of edges, this inner loop takes &lt;code&gt;O(E)&lt;/code&gt; time.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Therefore, the total time complexity for the Bellman Ford algorithm is &lt;strong&gt;O(V * E)&lt;/strong&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In a sparse graph (few edges), &lt;code&gt;E&lt;/code&gt; can be close to &lt;code&gt;V&lt;/code&gt;. So, &lt;code&gt;O(V^2)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;In a dense graph (many edges), &lt;code&gt;E&lt;/code&gt; can be up to &lt;code&gt;V^2&lt;/code&gt;. So, &lt;code&gt;O(V^3)&lt;/code&gt;.
However, the most generally accepted complexity is &lt;code&gt;O(VE)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;The space complexity of the Bellman Ford algorithm is relatively straightforward:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Distance Array:&lt;/strong&gt; An array &lt;code&gt;dist&lt;/code&gt; of size &lt;code&gt;V&lt;/code&gt; is used to store the shortest distances. This takes &lt;code&gt;O(V)&lt;/code&gt; space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edge List:&lt;/strong&gt; The graph itself is typically stored as a list of edges, which takes &lt;code&gt;O(E)&lt;/code&gt; space.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Thus, the total space complexity is &lt;strong&gt;O(V + E)&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Compared to Dijkstra's algorithm, which can achieve &lt;code&gt;O(E + V log V)&lt;/code&gt; with a min-priority queue, Bellman Ford is generally slower due to its &lt;code&gt;O(VE)&lt;/code&gt; complexity. However, its ability to handle negative weights and detect negative cycles often justifies the increased computational cost.&lt;/p&gt;
&lt;h2 id="common-mistakes-and-troubleshooting"&gt;Common Mistakes and Troubleshooting&lt;/h2&gt;
&lt;p&gt;When implementing or working with the Bellman Ford algorithm, several common pitfalls can lead to incorrect results or runtime errors. Being aware of these can help in effective troubleshooting.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Incorrect Initialization of Distances:&lt;/strong&gt; Forgetting to initialize the source distance to 0 and all other distances to &lt;code&gt;infinity&lt;/code&gt; is a frequent error. If &lt;code&gt;infinity&lt;/code&gt; is too small, sums with weights might overflow or incorrectly appear smaller than &lt;code&gt;infinity&lt;/code&gt;. Using &lt;code&gt;sys.maxsize&lt;/code&gt;, &lt;code&gt;Long.MAX_VALUE&lt;/code&gt;, or &lt;code&gt;std::numeric_limits&amp;lt;long long&amp;gt;::max()&lt;/code&gt; is crucial.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Off-by-One Errors in Loops:&lt;/strong&gt; The main relaxation loop must run exactly &lt;code&gt;V-1&lt;/code&gt; times. Running it &lt;code&gt;V&lt;/code&gt; times (before the negative cycle check) is not technically wrong but redundant in terms of finding shortest paths (if no negative cycles). Running it fewer than &lt;code&gt;V-1&lt;/code&gt; times might not find all shortest paths. The negative cycle check must be done in a &lt;em&gt;separate&lt;/em&gt; &lt;code&gt;V&lt;/code&gt;-th iteration.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Improper Negative Cycle Detection:&lt;/strong&gt; Not performing the &lt;code&gt;V&lt;/code&gt;-th iteration check for negative cycles, or performing it incorrectly, can lead to incorrect shortest path values being reported when a negative cycle exists. Always remember the distinction between &lt;code&gt;V-1&lt;/code&gt; relaxations for paths and the &lt;code&gt;V&lt;/code&gt;-th check for cycles.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Integer Overflow:&lt;/strong&gt; If edge weights or path sums can be large, using standard &lt;code&gt;int&lt;/code&gt; types might lead to overflow, especially when &lt;code&gt;dist[u] + w&lt;/code&gt; is calculated. Using &lt;code&gt;long&lt;/code&gt; in Java/C++ or Python's arbitrary-precision integers is recommended for the distance array to mitigate this.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graph Representation Issues:&lt;/strong&gt; Ensure your graph representation (e.g., list of edges, adjacency list) is correctly parsed and all edges are accessible during the relaxation phase. A common mistake is to only store edges in one direction if the graph is directed, but then incorrectly iterate over them as if they were undirected.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unreachable Nodes:&lt;/strong&gt; When &lt;code&gt;dist[u]&lt;/code&gt; remains &lt;code&gt;infinity&lt;/code&gt; (or &lt;code&gt;MAX_VALUE&lt;/code&gt;), it means vertex &lt;code&gt;u&lt;/code&gt; is unreachable from the source. Adding &lt;code&gt;dist[u]&lt;/code&gt; (infinity) to a weight &lt;code&gt;w&lt;/code&gt; can lead to overflow or incorrect comparisons if not handled by checking &lt;code&gt;dist[u] != INFINITY&lt;/code&gt; before relaxation.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="bellman-ford-vs-dijkstras-algorithm"&gt;Bellman Ford vs. Dijkstra's Algorithm&lt;/h2&gt;
&lt;p&gt;Both Bellman Ford and Dijkstra's algorithms solve the single-source shortest path problem, but they have distinct characteristics that make them suitable for different scenarios.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style="text-align: left;"&gt;Feature&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Bellman Ford Algorithm&lt;/th&gt;
&lt;th style="text-align: left;"&gt;Dijkstra's Algorithm&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Negative Edge Weights&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Handles them correctly.&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Does NOT handle them correctly.&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Negative Cycles&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Detects their presence.&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Cannot detect negative cycles and produces incorrect results if they exist.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Time Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(V * E)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(E + V log V)&lt;/code&gt; with a min-priority queue (Fibonacci heap), or &lt;code&gt;O(E log V)&lt;/code&gt; with a binary heap.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Space Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(V + E)&lt;/code&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;&lt;code&gt;O(V + E)&lt;/code&gt; (for adjacency list and priority queue)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Greedy Approach&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;No. Uses dynamic programming, iterative relaxation.&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Yes. Greedily selects the closest unvisited vertex.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Guaranteed Shortest Path&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Yes, if no negative cycles.&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Yes, if all edge weights are non-negative.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: left;"&gt;&lt;strong&gt;Applications&lt;/strong&gt;&lt;/td&gt;
&lt;td style="text-align: left;"&gt;Network routing (e.g., RIP protocol), arbitrage detection, graphs with negative costs.&lt;/td&gt;
&lt;td style="text-align: left;"&gt;GPS navigation, network shortest path calculations (where costs are positive), positive-weighted graphs.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;In summary, if your graph might contain negative edge weights or you need to detect negative cycles, Bellman Ford is the algorithm of choice. If all edge weights are guaranteed to be non-negative, Dijkstra's algorithm is typically preferred due to its superior performance.&lt;/p&gt;
&lt;h2 id="applications-of-bellman-ford"&gt;Applications of Bellman Ford&lt;/h2&gt;
&lt;p&gt;The Bellman Ford algorithm, despite its higher time complexity compared to Dijkstra's, finds critical applications in areas where negative edge weights or the detection of negative cycles are crucial.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Network Routing Protocols (e.g., RIP):&lt;/strong&gt; The Routing Information Protocol (RIP) in computer networks uses a variant of the Bellman Ford algorithm to determine the best routes for data packets. While RIP itself is a distance-vector routing protocol (which is a distributed version of Bellman Ford), it demonstrates the algorithm's utility in finding paths across networks where "cost" might be defined in complex ways, potentially involving negative values in more abstract network models.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Arbitrage Detection in Financial Markets:&lt;/strong&gt; In foreign exchange markets, arbitrage involves finding a sequence of trades that yields a risk-free profit. If currency exchange rates are modeled as edge weights (often as negative logarithms of exchange rates), a negative cycle in the resulting graph indicates an arbitrage opportunity. The Bellman Ford algorithm can effectively detect these cycles.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hazardous Materials Routing:&lt;/strong&gt; In scenarios involving the transportation of hazardous materials, certain paths might incur a "negative cost" if they allow for faster disposal or safer passage, effectively reducing overall risk or time. Bellman Ford can navigate these complex cost structures.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Constraint Satisfaction Problems:&lt;/strong&gt; In certain types of constraint satisfaction problems, especially those involving inequalities, the problem can be transformed into finding shortest paths in a graph where some "costs" can be negative, making Bellman Ford applicable.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These applications highlight that the unique capabilities of the Bellman Ford algorithm, particularly its robustness with negative weights and cycle detection, make it an invaluable tool in specific problem domains.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: Can Bellman Ford find the shortest path in an undirected graph with negative weights?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Bellman Ford is designed for directed graphs. For an undirected graph, each undirected edge &lt;code&gt;(u, v)&lt;/code&gt; with weight &lt;code&gt;w&lt;/code&gt; is typically represented as two directed edges &lt;code&gt;(u, v, w)&lt;/code&gt; and &lt;code&gt;(v, u, w)&lt;/code&gt;. If &lt;code&gt;w&lt;/code&gt; is negative, this creates an immediate negative cycle between &lt;code&gt;u&lt;/code&gt; and &lt;code&gt;v&lt;/code&gt;, making shortest paths undefined if you can traverse &lt;code&gt;u -&amp;gt; v -&amp;gt; u&lt;/code&gt; infinitely for a decreasing cost. Therefore, Bellman Ford is generally not applied to undirected graphs with negative edges.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What happens if there are multiple shortest paths to a vertex?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: If multiple paths yield the same minimum distance to a vertex, Bellman Ford will correctly identify one of them. The specific path recorded might depend on the order in which edges are relaxed, but the final distance will be the same shortest distance.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Is Bellman Ford suitable for very large graphs?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Due to its &lt;code&gt;O(V*E)&lt;/code&gt; time complexity, Bellman Ford can become inefficient for very large graphs compared to Dijkstra's &lt;code&gt;O(E + V log V)&lt;/code&gt; when negative weights are not an issue. For extremely large graphs, specialized algorithms or heuristics might be required, or for specific cases like single-source-single-destination, bidirectional search variants might be more efficient.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;Bellman Ford Algorithm in Python, C++, Java&lt;/strong&gt; is a cornerstone in graph theory, offering a robust solution to the single-source shortest path problem, even in the presence of negative edge weights. This tutorial has walked you through its theoretical foundations, detailed implementation steps, and provided clear code examples across Python, C++, and Java. We've explored its unique ability to detect negative cycles, a critical feature that differentiates it from other algorithms like Dijkstra's.&lt;/p&gt;
&lt;p&gt;By mastering Bellman Ford, you gain a powerful tool for analyzing complex networks, optimizing routes with varied costs, and even detecting opportunities in financial markets. Remember its &lt;code&gt;O(VE)&lt;/code&gt; time complexity and its necessity when dealing with negative weights. Armed with this knowledge and the provided implementations, you are now well-equipped to apply the Bellman Ford algorithm to a wide array of computational challenges. Keep practicing, and explore more advanced graph algorithms to expand your problem-solving toolkit!&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Wikipedia:&lt;/strong&gt; &lt;a href="https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm"&gt;Bellman-Ford Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;GeeksForGeeks:&lt;/strong&gt; &lt;a href="https://www.geeksforgeeks.org/bellman-ford-algorithm-set-1-shortest-path-given-source-unreachable-destination/"&gt;Bellman-Ford Algorithm | Set 1 (Introduction and Working)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Introduction to Algorithms (CLRS):&lt;/strong&gt; Chapter 24, "Single-Source Shortest Paths". A classic textbook for in-depth algorithmic theory.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Baeldung:&lt;/strong&gt; &lt;a href="https://www.baeldung.com/java-bellman-ford"&gt;The Bellman-Ford Algorithm in Java&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Problem Solving"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/bellman-ford-algorithm-python-cpp-java-tutorial.webp" width="1200"/><media:title type="plain">Bellman Ford Algorithm in Python, C++, Java: A Complete Tutorial</media:title><media:description type="plain">Master the Bellman Ford Algorithm in Python, C++, and Java. This comprehensive tutorial covers implementation, time complexity, and handling negative cycles.</media:description></entry><entry><title>Segment Tree in Python, Java &amp; C++: A Comprehensive Guide</title><link href="https://analyticsdrive.tech/segment-tree-tutorial-python-java-cpp/" rel="alternate"/><published>2026-02-26T15:39:00+05:30</published><updated>2026-04-21T04:43:51.641635+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-26:/segment-tree-tutorial-python-java-cpp/</id><summary type="html">&lt;p&gt;Master the Segment Tree data structure in Python, Java, and C++ with this comprehensive guide. Learn its operations, applications, and efficient implementations.&lt;/p&gt;</summary><content type="html">&lt;p&gt;In the realm of algorithms and data structures, efficiently handling range queries and updates is a common challenge that developers and students frequently encounter. Whether you're tackling competitive programming problems, designing performant systems, or optimizing database operations, the ability to quickly retrieve information from a range or modify elements within it can be crucial. This is precisely where the &lt;strong&gt;Segment Tree in Python, Java &amp;amp; C++&lt;/strong&gt; emerges as an indispensable tool, offering a powerful and elegant solution. This comprehensive guide will walk you through the intricacies of Segment Trees, detailing their core concepts, fundamental operations, and practical implementations across these three popular programming languages.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#understanding-the-segment-tree-what-is-it"&gt;Understanding the Segment Tree: What Is It?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#why-master-segment-trees-advantages-and-use-cases"&gt;Why Master Segment Trees? Advantages and Use Cases&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#advantages-of-segment-trees"&gt;Advantages of Segment Trees&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-use-cases"&gt;Common Use Cases&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-learning-segment-trees"&gt;Prerequisites for Learning Segment Trees&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-operations-of-a-segment-tree"&gt;Core Operations of a Segment Tree&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-building-the-segment-tree-on-complexity"&gt;1. Building the Segment Tree (O(N) Complexity)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-querying-a-range-olog-n-complexity"&gt;2. Querying a Range (O(log N) Complexity)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-updating-an-element-olog-n-complexity"&gt;3. Updating an Element (O(log N) Complexity)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-a-segment-tree-in-python-java-and-c"&gt;Implementing a Segment Tree in Python, Java and C++&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#segment-tree-implementation-in-python"&gt;Segment Tree Implementation in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#segment-tree-implementation-in-java"&gt;Segment Tree Implementation in Java&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#segment-tree-implementation-in-c"&gt;Segment Tree Implementation in C++&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-pitfalls-and-how-to-avoid-them"&gt;Common Pitfalls and How to Avoid Them&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#expanding-your-knowledge-advanced-segment-tree-concepts"&gt;Expanding Your Knowledge: Advanced Segment Tree Concepts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion-mastering-segment-trees-for-data-efficiency"&gt;Conclusion: Mastering Segment Trees for Data Efficiency&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;p&gt;A Segment Tree is a versatile data structure that allows for two primary operations on an array: querying for a range sum, minimum, maximum, or other aggregate values, and updating individual elements or entire ranges. Unlike simpler approaches like prefix sums, which excel at range queries but struggle with updates, or plain arrays, which are slow for both, a Segment Tree strikes an impressive balance, performing both in logarithmic time complexity. This makes it a preferred choice for scenarios demanding high performance in both aspects. We will delve deep into its recursive construction, efficient query mechanisms, and point-update procedures, ensuring you gain a solid understanding that extends beyond mere theoretical knowledge into practical application. By the end of this tutorial, you will be well-equipped to implement and utilize Segment Trees effectively in your coding endeavors, mastering a technique essential for robust algorithm design.&lt;/p&gt;
&lt;h2 id="understanding-the-segment-tree-what-is-it"&gt;Understanding the Segment Tree: What Is It?&lt;/h2&gt;
&lt;p&gt;At its core, a Segment Tree is a binary tree designed specifically for storing information about intervals or segments. Each node in the tree represents an interval, with the root representing the entire array or segment of interest. Its children then represent sub-intervals, effectively dividing the original segment into two halves. This recursive division continues until the leaf nodes are reached, each representing a single element from the original array.&lt;/p&gt;
&lt;p&gt;Consider an array &lt;code&gt;A = [1, 3, 5, 7, 9, 11]&lt;/code&gt;. A Segment Tree built upon this array would have its root node representing the interval &lt;code&gt;[0, 5]&lt;/code&gt; (the entire array). Its left child might represent &lt;code&gt;[0, 2]&lt;/code&gt; and its right child &lt;code&gt;[3, 5]&lt;/code&gt;. This pattern repeats, with nodes storing an aggregate value (like sum, minimum, or maximum) for their respective intervals. For example, if we're building a sum Segment Tree, the root node would store &lt;code&gt;1 + 3 + 5 + 7 + 9 + 11 = 36&lt;/code&gt;, while its left child &lt;code&gt;[0, 2]&lt;/code&gt; would store &lt;code&gt;1 + 3 + 5 = 9&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The power of the Segment Tree lies in this hierarchical structure. When you need to query a range, say &lt;code&gt;[1, 4]&lt;/code&gt;, the tree can efficiently combine pre-computed results from relevant nodes without needing to iterate through every element in the original array. Similarly, when an element is updated, only the nodes whose segments contain that element need to have their aggregate values recomputed, which, due to the tree's structure, only affects a logarithmic number of nodes. This contrasts sharply with a naive approach that might iterate &lt;code&gt;O(N)&lt;/code&gt; elements for queries or updates, or a prefix sum array that requires &lt;code&gt;O(N)&lt;/code&gt; updates after each element change.&lt;/p&gt;
&lt;h2 id="why-master-segment-trees-advantages-and-use-cases"&gt;Why Master Segment Trees? Advantages and Use Cases&lt;/h2&gt;
&lt;p&gt;Mastering Segment Trees is a significant step towards becoming a more proficient problem-solver and engineer. Their unique properties make them invaluable in various computational scenarios.&lt;/p&gt;
&lt;h3 id="advantages-of-segment-trees"&gt;Advantages of Segment Trees&lt;/h3&gt;
&lt;p&gt;Segment Trees offer several distinct advantages over other data structures when dealing with range-based operations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Efficient Range Queries:&lt;/strong&gt; They can answer queries such as range sum, range minimum, range maximum, range product, range GCD, etc., in &lt;code&gt;O(log N)&lt;/code&gt; time. This is a significant improvement over &lt;code&gt;O(N)&lt;/code&gt; for naive array traversal.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Efficient Point and Range Updates:&lt;/strong&gt; Updating a single element or a range of elements (with lazy propagation) also takes &lt;code&gt;O(log N)&lt;/code&gt; time. This rapid update capability maintains the tree's utility even in dynamic scenarios.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Versatility:&lt;/strong&gt; The underlying structure is adaptable to various operations. By changing how child results are combined, a Segment Tree can support a wide array of aggregate functions, not just sums.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Space Efficiency:&lt;/strong&gt; While it uses more space than the original array, typically &lt;code&gt;O(4N)&lt;/code&gt; or &lt;code&gt;O(2*2^ceil(log2(N)))&lt;/code&gt;, it's still a practical and manageable amount for most problem sizes. This slight overhead is often a worthwhile trade-off for the time complexity gains.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Foundation for Advanced Techniques:&lt;/strong&gt; Understanding basic Segment Trees is a prerequisite for more advanced data structures like Lazy Propagation Segment Trees, Persistent Segment Trees, and Merge Sort Trees, which extend their capabilities even further.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="common-use-cases"&gt;Common Use Cases&lt;/h3&gt;
&lt;p&gt;The practical applications of Segment Trees span across various domains:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Competitive Programming:&lt;/strong&gt; This is perhaps the most common arena where Segment Trees shine. Many problems involve optimizing queries and updates on ranges, and Segment Trees frequently provide the optimal solution, similar to how other fundamental algorithms like the &lt;a href="/dijkstra-algorithm-python-cpp-java-tutorial/"&gt;Dijkstra Algorithm in Python, C++, Java&lt;/a&gt; are crucial for competitive programming. Examples include finding the maximum element in a subarray, counting inversions, or solving complex interval-scheduling problems.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Real-time Analytics:&lt;/strong&gt; In systems where data streams are constantly changing and aggregate statistics for specific time windows or data ranges are needed instantly, Segment Trees can maintain these aggregates efficiently.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Game Development:&lt;/strong&gt; Spatial queries, collision detection, and managing dynamic game elements that occupy regions can benefit from Segment Tree-like structures, although often more specialized spatial indexing structures are used (like Quadtrees or Octrees). The underlying principle of dividing space and querying sub-regions holds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Database Management Systems (DBMS):&lt;/strong&gt; While not directly used as the primary indexing structure (B-trees and B+ trees are common), the conceptual idea of efficiently querying and updating data over intervals is central to how many query optimizers and data warehouses function. Segment Trees provide an excellent model for understanding these mechanisms.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Geographical Information Systems (GIS):&lt;/strong&gt; Similar to game development, querying geographical regions for specific features or properties can be optimized using structures that partition space hierarchically.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="prerequisites-for-learning-segment-trees"&gt;Prerequisites for Learning Segment Trees&lt;/h2&gt;
&lt;p&gt;Before diving into the implementation details of Segment Trees, it's beneficial to have a solid grasp of a few foundational concepts. These prerequisites will ensure you can fully comprehend the logic and structure involved:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Basic Understanding of Arrays:&lt;/strong&gt; Segment Trees are fundamentally built upon arrays. You should be comfortable with array indexing, traversing arrays, and basic array operations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Binary Trees:&lt;/strong&gt; A Segment Tree is, as its name suggests, a binary tree. Familiarity with binary tree terminology (root, node, parent, child, leaf, height, depth), basic properties (at most two children per node), and common traversals (in-order, pre-order, post-order) is crucial.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursion:&lt;/strong&gt; The build, query, and update operations of a Segment Tree are inherently recursive. A strong understanding of recursion, including base cases, recursive calls, and how results are combined, is absolutely essential. If you're new to recursion, practicing problems like calculating factorials or traversing simple trees will be helpful.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Divide and Conquer Paradigm:&lt;/strong&gt; Segment Trees exemplify the divide and conquer approach. Understanding how a problem can be broken down into smaller, similar subproblems, solved independently, and then combined to form the final solution is key to grasping the Segment Tree's operational philosophy.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Basic Data Structures:&lt;/strong&gt; General familiarity with common data structures like lists, stacks, and queues will help put Segment Trees into context within the broader landscape of algorithms.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With these prerequisites in place, including a good grasp of concepts fundamental to algorithmic problem-solving such as those explored in the &lt;a href="/cses-labyrinth-problem-python-java-cpp-guide/"&gt;CSES Labyrinth Problem in Python, Java &amp;amp; C++&lt;/a&gt;, you'll find the journey of learning and implementing Segment Trees much smoother and more rewarding.&lt;/p&gt;
&lt;h2 id="core-operations-of-a-segment-tree"&gt;Core Operations of a Segment Tree&lt;/h2&gt;
&lt;p&gt;A Segment Tree supports three primary operations: building the tree, querying a range, and updating an element. Each of these operations leverages the tree's recursive, divide-and-conquer nature to achieve logarithmic time complexity.&lt;/p&gt;
&lt;h3 id="1-building-the-segment-tree-on-complexity"&gt;1. Building the Segment Tree (O(N) Complexity)&lt;/h3&gt;
&lt;p&gt;The construction of a Segment Tree is typically a recursive process. It starts with the root node, representing the entire input array.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Base Case:&lt;/strong&gt; If the current segment consists of a single element (i.e., &lt;code&gt;start == end&lt;/code&gt;), the current node is a leaf node. Its value is simply the value of that element from the original array.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursive Step:&lt;/strong&gt; If the segment has more than one element (&lt;code&gt;start &amp;lt; end&lt;/code&gt;):&lt;ol&gt;
&lt;li&gt;Divide the current segment &lt;code&gt;[start, end]&lt;/code&gt; into two halves: &lt;code&gt;[start, mid]&lt;/code&gt; and &lt;code&gt;[mid+1, end]&lt;/code&gt;, where &lt;code&gt;mid = (start + end) // 2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Recursively build the left child for &lt;code&gt;[start, mid]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Recursively build the right child for &lt;code&gt;[mid+1, end]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The value of the current node is then computed by combining the values of its left and right children. For a sum Segment Tree, this would be &lt;code&gt;node.value = left_child.value + right_child.value&lt;/code&gt;. For a minimum Segment Tree, &lt;code&gt;node.value = min(left_child.value, right_child.value)&lt;/code&gt;, and so on.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This process ensures that every node correctly stores the aggregate value for its corresponding segment. Since each element in the original array is visited once to become a leaf, and each internal node is created by combining two children, the total time complexity for building the tree is &lt;code&gt;O(N)&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="2-querying-a-range-olog-n-complexity"&gt;2. Querying a Range (O(log N) Complexity)&lt;/h3&gt;
&lt;p&gt;To query for an aggregate value within a specific range &lt;code&gt;[query_L, query_R]&lt;/code&gt;, the Segment Tree employs a recursive search. The function typically takes the current node's segment &lt;code&gt;[node_start, node_end]&lt;/code&gt; and the target query range &lt;code&gt;[query_L, query_R]&lt;/code&gt; as parameters.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Case 1: No Overlap:&lt;/strong&gt; If the current node's segment &lt;code&gt;[node_start, node_end]&lt;/code&gt; is completely outside the query range &lt;code&gt;[query_L, query_R]&lt;/code&gt; (e.g., &lt;code&gt;node_end &amp;lt; query_L&lt;/code&gt; or &lt;code&gt;node_start &amp;gt; query_R&lt;/code&gt;), then this node contributes nothing to the query. Return an identity value (e.g., 0 for sum, infinity for min, negative infinity for max).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Case 2: Complete Overlap:&lt;/strong&gt; If the current node's segment &lt;code&gt;[node_start, node_end]&lt;/code&gt; is entirely contained within the query range &lt;code&gt;[query_L, query_R]&lt;/code&gt; (e.g., &lt;code&gt;query_L &amp;lt;= node_start&lt;/code&gt; and &lt;code&gt;node_end &amp;lt;= query_R&lt;/code&gt;), then the value stored in this node is exactly what's needed. Return &lt;code&gt;node.value&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Case 3: Partial Overlap:&lt;/strong&gt; If there's a partial overlap, the query needs to be resolved by recursively querying the children.&lt;ol&gt;
&lt;li&gt;Calculate &lt;code&gt;mid = (node_start + node_end) // 2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Recursively query the left child for the range &lt;code&gt;[query_L, query_R]&lt;/code&gt; over its segment &lt;code&gt;[node_start, mid]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Recursively query the right child for the range &lt;code&gt;[query_L, query_R]&lt;/code&gt; over its segment &lt;code&gt;[mid+1, node_end]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Combine the results from the left and right child queries. For a sum query, &lt;code&gt;result = left_query_result + right_query_result&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Because each step either returns a value or recurses into at most two children, and the tree has a height of &lt;code&gt;O(log N)&lt;/code&gt;, the query operation takes &lt;code&gt;O(log N)&lt;/code&gt; time.&lt;/p&gt;
&lt;h3 id="3-updating-an-element-olog-n-complexity"&gt;3. Updating an Element (O(log N) Complexity)&lt;/h3&gt;
&lt;p&gt;Updating a single element at a specific index &lt;code&gt;idx&lt;/code&gt; to a new &lt;code&gt;value&lt;/code&gt; also follows a recursive path, starting from the root.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Base Case:&lt;/strong&gt; If the current node's segment is a leaf node (i.e., &lt;code&gt;node_start == node_end == idx&lt;/code&gt;), then this is the node corresponding to the element to be updated. Update its stored value to &lt;code&gt;new_value&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursive Step:&lt;/strong&gt; If the current node is not a leaf node:&lt;ol&gt;
&lt;li&gt;Calculate &lt;code&gt;mid = (node_start + node_end) // 2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Determine which child's segment contains &lt;code&gt;idx&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;idx &amp;lt;= mid&lt;/code&gt;, recursively call update on the left child.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;idx &amp;gt; mid&lt;/code&gt;, recursively call update on the right child.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;After the recursive call returns (meaning the child's value has been updated), recompute the current node's value by combining the (potentially updated) values of its left and right children. This ensures the aggregate values are correct all the way up to the root.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Similar to queries, an update operation traverses a single path from the root to a leaf, and then updates values back up the same path. Therefore, it also takes &lt;code&gt;O(log N)&lt;/code&gt; time. For range updates, a more advanced technique called "Lazy Propagation" is used, which extends these concepts but is beyond the scope of a basic Segment Tree tutorial.&lt;/p&gt;
&lt;h2 id="implementing-a-segment-tree-in-python-java-and-c"&gt;Implementing a Segment Tree in Python, Java and C++&lt;/h2&gt;
&lt;p&gt;This section provides comprehensive implementations of the &lt;strong&gt;Segment Tree in Python, Java and C++&lt;/strong&gt;, focusing on a sum query example. Each implementation will include the &lt;code&gt;build&lt;/code&gt;, &lt;code&gt;query&lt;/code&gt;, and &lt;code&gt;update&lt;/code&gt; operations.&lt;/p&gt;
&lt;h3 id="segment-tree-implementation-in-python"&gt;Segment Tree Implementation in Python&lt;/h3&gt;
&lt;p&gt;Python's flexibility makes Segment Tree implementation concise and readable. We'll use a list to represent the tree nodes, where &lt;code&gt;tree[i]&lt;/code&gt; stores the aggregate value for a segment. Node &lt;code&gt;i&lt;/code&gt; has left child &lt;code&gt;2*i + 1&lt;/code&gt; and right child &lt;code&gt;2*i + 2&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SegmentTree&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="fm"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="c1"&gt;# Tree array size is usually 4*N for worst-case,&lt;/span&gt;
        &lt;span class="c1"&gt;# but 2*2^ceil(log2(N)) is more precise.&lt;/span&gt;
        &lt;span class="c1"&gt;# For competitive programming, 4*N is standard and safe.&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Recursively builds the segment tree.&lt;/span&gt;
&lt;span class="sd"&gt;        node_idx: current node&amp;#39;s index in self.tree&lt;/span&gt;
&lt;span class="sd"&gt;        start, end: interval represented by current node&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="c1"&gt;# Leaf node: store array element&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
            &lt;span class="c1"&gt;# Build left child&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="c1"&gt;# Build right child&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="c1"&gt;# Current node value is sum of children&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Updates the value at a specific index in the original array and&lt;/span&gt;
&lt;span class="sd"&gt;        propagates changes up the tree.&lt;/span&gt;
&lt;span class="sd"&gt;        idx: index in original array to update&lt;/span&gt;
&lt;span class="sd"&gt;        val: new value&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="c1"&gt;# Update original array&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Recursive helper for update.&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="c1"&gt;# Leaf node, update its value&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;idx&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="c1"&gt;# idx is in the left child&amp;#39;s segment&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="c1"&gt;# idx is in the right child&amp;#39;s segment&lt;/span&gt;
                &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="c1"&gt;# Update current node after children are updated&lt;/span&gt;
            &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Queries the sum of elements in a given range [L, R].&lt;/span&gt;
&lt;span class="sd"&gt;        L, R: query range (inclusive)&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;        Recursive helper for query.&lt;/span&gt;
&lt;span class="sd"&gt;        &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
        &lt;span class="c1"&gt;# Case 1: No overlap&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;R&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;  &lt;span class="c1"&gt;# Return identity for sum (0)&lt;/span&gt;
        &lt;span class="c1"&gt;# Case 2: Complete overlap&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;L&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="c1"&gt;# Case 3: Partial overlap&lt;/span&gt;
        &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
        &lt;span class="n"&gt;p1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;p2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;node_idx&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;p1&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;p2&lt;/span&gt;

&lt;span class="c1"&gt;# Example Usage in Python:&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="vm"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;__main__&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;arr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;st&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;SegmentTree&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Original array: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Sum of range [1, 4]: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Should be 3 + 5 + 7 + 9 = 24&lt;/span&gt;

    &lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Update arr[2] from 5 to 10&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Array after update at index 2 to 10: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# arr becomes [1, 3, 10, 7, 9, 11]&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Sum of range [1, 4] after update: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Should be 3 + 10 + 7 + 9 = 29&lt;/span&gt;

    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Sum of full array [0, 5]: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Should be 1 + 3 + 10 + 7 + 9 + 11 = 41&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Explanation for Python Implementation:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;__init__(self, arr)&lt;/code&gt;:&lt;/strong&gt; Initializes the SegmentTree. &lt;code&gt;self.n&lt;/code&gt; stores the size of the input array. &lt;code&gt;self.tree&lt;/code&gt; is an array that will store the Segment Tree nodes. It's allocated &lt;code&gt;4 * self.n&lt;/code&gt; space to safely accommodate any tree size up to &lt;code&gt;N&lt;/code&gt;. The &lt;code&gt;_build&lt;/code&gt; method is called to construct the tree.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;_build(self, node_idx, start, end)&lt;/code&gt;:&lt;/strong&gt; This recursive function builds the tree.&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;node_idx&lt;/code&gt; refers to the current node's position in &lt;code&gt;self.tree&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;start&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt; define the segment of the original &lt;code&gt;arr&lt;/code&gt; that &lt;code&gt;self.tree[node_idx]&lt;/code&gt; represents.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;start == end&lt;/code&gt;, it's a leaf node, and its value is taken directly from &lt;code&gt;arr[start]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Otherwise, it recursively builds left and right children, then computes &lt;code&gt;self.tree[node_idx]&lt;/code&gt; as the sum of its children's values.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;update(self, idx, val)&lt;/code&gt;:&lt;/strong&gt; This is the public interface for updating an element. It first updates the &lt;code&gt;self.arr&lt;/code&gt; (the original array) and then calls the private &lt;code&gt;_update&lt;/code&gt; helper.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;_update(self, node_idx, start, end, idx, val)&lt;/code&gt;:&lt;/strong&gt; This recursive helper updates the tree.&lt;ul&gt;
&lt;li&gt;It traverses down to the leaf node corresponding to &lt;code&gt;idx&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Once the leaf is found (&lt;code&gt;start == end&lt;/code&gt;), its value in &lt;code&gt;self.tree&lt;/code&gt; is updated.&lt;/li&gt;
&lt;li&gt;As the recursion unwinds, parent nodes' values are recomputed based on their children.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;query(self, L, R)&lt;/code&gt;:&lt;/strong&gt; The public interface for querying a range. It calls the private &lt;code&gt;_query&lt;/code&gt; helper.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;_query(self, node_idx, start, end, L, R)&lt;/code&gt;:&lt;/strong&gt; This recursive helper performs the range query.&lt;ul&gt;
&lt;li&gt;It checks for three cases: no overlap, complete overlap, or partial overlap with the query range &lt;code&gt;[L, R]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If no overlap, it returns 0 (the identity element for sum).&lt;/li&gt;
&lt;li&gt;If complete overlap, it returns the node's stored value.&lt;/li&gt;
&lt;li&gt;If partial overlap, it recursively queries both children and sums their results.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="segment-tree-implementation-in-java"&gt;Segment Tree Implementation in Java&lt;/h3&gt;
&lt;p&gt;Java requires explicit class definitions for nodes or a clear indexing scheme. We'll use an array-based approach similar to Python, but with explicit method signatures and type declarations.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SegmentTree&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;SegmentTree&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;arr&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;tree&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Max size for segment tree&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;throw&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;IndexOutOfBoundsException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Index &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; is out of bounds for array of size &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Update original array&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;throw&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;IllegalArgumentException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Invalid query range [&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;] for array of size &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Case 1: No overlap&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Identity for sum&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Case 2: Complete overlap&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Case 3: Partial overlap&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example Usage in Java:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;SegmentTree&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;SegmentTree&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Original array: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;util&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Sum of range [1, 4]: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Should be 24&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Update arr[2] from 5 to 10&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Array after update at index 2 to 10: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;util&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// arr becomes [1, 3, 10, 7, 9, 11]&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Sum of range [1, 4] after update: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Should be 29&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Sum of full array [0, 5]: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Should be 41&lt;/span&gt;
&lt;span class="w"&gt;    &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;&lt;strong&gt;Explanation for Java Implementation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The Java implementation mirrors the Python one closely in logic.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Class &lt;code&gt;SegmentTree&lt;/code&gt;:&lt;/strong&gt; Contains &lt;code&gt;arr&lt;/code&gt; (original array), &lt;code&gt;tree&lt;/code&gt; (segment tree array), and &lt;code&gt;n&lt;/code&gt; (array size).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Constructor &lt;code&gt;SegmentTree(int[] arr)&lt;/code&gt;:&lt;/strong&gt; Initializes these fields and calls the &lt;code&gt;build&lt;/code&gt; method.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;build(int nodeIdx, int start, int end)&lt;/code&gt;:&lt;/strong&gt; Recursive method to construct the tree. Identical logic to Python.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;update(int idx, int val)&lt;/code&gt; (public &amp;amp; private):&lt;/strong&gt; The public &lt;code&gt;update&lt;/code&gt; method handles basic validation and updates the original &lt;code&gt;arr&lt;/code&gt;, then calls the private recursive &lt;code&gt;update&lt;/code&gt; helper. The recursive helper finds the leaf node and propagates changes upwards.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;query(int L, int R)&lt;/code&gt; (public &amp;amp; private):&lt;/strong&gt; The public &lt;code&gt;query&lt;/code&gt; method validates input range and then calls the private recursive &lt;code&gt;query&lt;/code&gt; helper. The recursive helper uses the same three-case logic (no overlap, complete overlap, partial overlap) to efficiently sum the range.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="segment-tree-implementation-in-c"&gt;Segment Tree Implementation in C++&lt;/h3&gt;
&lt;p&gt;C++ offers performance benefits and explicit memory management. We'll use &lt;code&gt;std::vector&lt;/code&gt; for the array-based tree implementation.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;numeric&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // For std::accumulate (optional, for verification)&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;SegmentTree&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Avoids potential overflow&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;update_helper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;update_helper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;update_helper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;query_helper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Case 1: No overlap&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Identity for sum&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Case 2: Complete overlap&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Case 3: Partial overlap&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query_helper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query_helper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;p2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;SegmentTree&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;input_arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;input_arr&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Copy the input array&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;resize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Allocate memory for the tree, initialize with 0&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cerr&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Error: Index &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; out of bounds.&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Update original array&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;update_helper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cerr&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Error: Invalid query range [&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;].&amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Return identity in case of error&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;query_helper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;R&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;// Example Usage in C++:&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;SegmentTree&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Original array: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Sum of range [1, 4]: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Should be 24&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Update arr[2] from 5 to 10&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Array after update at index 2 to 10: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Manually update for consistent print as `st.arr` is a copy&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Sum of range [1, 4] after update: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Should be 29&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Sum of full array [0, 5]: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;st&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Should be 41&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&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;&lt;strong&gt;Explanation for C++ Implementation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The C++ implementation closely follows the Java and Python logic.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Class &lt;code&gt;SegmentTree&lt;/code&gt;:&lt;/strong&gt; Uses &lt;code&gt;std::vector&amp;lt;int&amp;gt;&lt;/code&gt; for &lt;code&gt;arr&lt;/code&gt; and &lt;code&gt;tree&lt;/code&gt;. &lt;code&gt;n&lt;/code&gt; stores the size.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;build&lt;/code&gt; method:&lt;/strong&gt; A private recursive helper to construct the tree. The &lt;code&gt;mid&lt;/code&gt; calculation &lt;code&gt;start + (end - start) / 2&lt;/code&gt; is a common C++ idiom to prevent integer overflow that &lt;code&gt;(start + end) / 2&lt;/code&gt; might cause with very large &lt;code&gt;start&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt; values.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;update_helper&lt;/code&gt; and &lt;code&gt;query_helper&lt;/code&gt;:&lt;/strong&gt; Private recursive methods implementing the update and query logic, respectively.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Constructor &lt;code&gt;SegmentTree(const std::vector&amp;lt;int&amp;gt;&amp;amp; input_arr)&lt;/code&gt;:&lt;/strong&gt; Takes a constant reference to the input array, copies it to &lt;code&gt;this-&amp;gt;arr&lt;/code&gt;, sets &lt;code&gt;n&lt;/code&gt;, and resizes &lt;code&gt;tree&lt;/code&gt; to &lt;code&gt;4 * n&lt;/code&gt; before calling &lt;code&gt;build&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Public &lt;code&gt;update(int idx, int val)&lt;/code&gt; and &lt;code&gt;query(int L, int R)&lt;/code&gt;:&lt;/strong&gt; These methods provide user-friendly interfaces, including basic bounds checking and error messages using &lt;code&gt;std::cerr&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;main&lt;/code&gt; function:&lt;/strong&gt; Demonstrates usage with an example array, performing queries and an update, then re-querying. Note that &lt;code&gt;arr[2] = 10;&lt;/code&gt; is explicitly added in &lt;code&gt;main&lt;/code&gt; to reflect the updated value when printing the "original array" after the update, as the &lt;code&gt;SegmentTree&lt;/code&gt; class holds its own copy of the array.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="common-pitfalls-and-how-to-avoid-them"&gt;Common Pitfalls and How to Avoid Them&lt;/h2&gt;
&lt;p&gt;Implementing a Segment Tree can be tricky, and several common mistakes often trip up beginners. Awareness of these pitfalls can save significant debugging time.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Off-by-One Errors in Indexing:&lt;/strong&gt; This is perhaps the most frequent issue.&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem:&lt;/strong&gt; Confusion between 0-based and 1-based indexing for arrays and tree nodes. Miscalculation of &lt;code&gt;mid&lt;/code&gt; (e.g., &lt;code&gt;(start + end) / 2&lt;/code&gt; vs. &lt;code&gt;start + (end - start) / 2&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; Stick consistently to either 0-based or 1-based indexing for &lt;em&gt;all&lt;/em&gt; operations (array, tree, query ranges). The provided examples use 0-based indexing for the original array and tree nodes. For &lt;code&gt;mid&lt;/code&gt;, &lt;code&gt;start + (end - start) / 2&lt;/code&gt; is generally safer, especially in C++/Java. Always double-check boundary conditions: &lt;code&gt;start &amp;lt;= idx &amp;lt;= mid&lt;/code&gt; vs. &lt;code&gt;mid + 1 &amp;lt;= idx &amp;lt;= end&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Incorrect Base Cases in Recursion:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem:&lt;/strong&gt; The base case for &lt;code&gt;build&lt;/code&gt;, &lt;code&gt;query&lt;/code&gt;, and &lt;code&gt;update&lt;/code&gt; (when &lt;code&gt;start == end&lt;/code&gt;) might be handled incorrectly, leading to infinite recursion or incorrect leaf values.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; For &lt;code&gt;build&lt;/code&gt; and &lt;code&gt;update&lt;/code&gt;, when &lt;code&gt;start == end&lt;/code&gt;, the node's value should directly correspond to &lt;code&gt;arr[start]&lt;/code&gt; (or the updated value). For &lt;code&gt;query&lt;/code&gt;, if &lt;code&gt;start == end&lt;/code&gt; and it falls within the query range, return &lt;code&gt;tree[node_idx]&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Forgetting to Update Parent Nodes:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem:&lt;/strong&gt; In the &lt;code&gt;update&lt;/code&gt; operation, after a child node's value is changed, it's crucial to recompute the parent node's value by combining its children. Forgetting this step results in an inconsistent tree.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; Ensure that after every recursive call to &lt;code&gt;update&lt;/code&gt; (for both left and right children), there's a line like &lt;code&gt;tree[node_idx] = tree[2*node_idx + 1] + tree[2*node_idx + 2]&lt;/code&gt; (or equivalent for other operations) to propagate the changes upwards.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Incorrect Identity Element for Queries:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem:&lt;/strong&gt; When a query range falls completely outside a node's segment, the function must return an "identity" value that doesn't affect the final result. For sum, it's 0. For minimum, it's positive infinity. For maximum, it's negative infinity. Using the wrong identity can lead to incorrect query results.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; Always define and use the correct identity element specific to the aggregate operation (e.g., &lt;code&gt;0&lt;/code&gt; for sum, &lt;code&gt;Integer.MAX_VALUE&lt;/code&gt; or &lt;code&gt;LLONG_MAX&lt;/code&gt; for minimum, &lt;code&gt;Integer.MIN_VALUE&lt;/code&gt; or &lt;code&gt;LLONG_MIN&lt;/code&gt; for maximum).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Integer Overflow:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem:&lt;/strong&gt; Especially in C++ and Java, if you are summing a large number of integers, the sum might exceed the maximum value of &lt;code&gt;int&lt;/code&gt;, leading to incorrect results or unexpected behavior.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; If there's a possibility of large sums, use &lt;code&gt;long&lt;/code&gt; (Java) or &lt;code&gt;long long&lt;/code&gt; (C++) for the array elements and the &lt;code&gt;tree&lt;/code&gt; array.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Stack Overflow with Very Large Arrays:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem:&lt;/strong&gt; Although rare for typical competitive programming constraints (N &amp;lt;= 10^5 to 10^6), extremely large arrays could theoretically cause a stack overflow due to deep recursion.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; In practice, this is seldom an issue with Segment Trees due to their &lt;code&gt;log N&lt;/code&gt; depth. For truly massive &lt;code&gt;N&lt;/code&gt;, an iterative Segment Tree (often built on similar principles to Fenwick trees) might be considered, but generally recursion is fine.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory Usage:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem:&lt;/strong&gt; The &lt;code&gt;4 * N&lt;/code&gt; memory allocation for the &lt;code&gt;tree&lt;/code&gt; array can be substantial for very large &lt;code&gt;N&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution:&lt;/strong&gt; Be mindful of memory limits. While &lt;code&gt;4*N&lt;/code&gt; is typical, if &lt;code&gt;N&lt;/code&gt; is extremely large (e.g., &lt;code&gt;10^7&lt;/code&gt;), &lt;code&gt;4 * 10^7&lt;/code&gt; integers might exceed memory limits. In such cases, alternative solutions or sparse Segment Tree variants might be necessary, but for &lt;code&gt;N&lt;/code&gt; up to &lt;code&gt;10^6&lt;/code&gt;, it's usually acceptable (e.g., &lt;code&gt;4 * 10^6 * 4 bytes/int = 16MB&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;By carefully reviewing your code against these common pitfalls, you can significantly reduce debugging time and build more robust Segment Tree implementations.&lt;/p&gt;
&lt;h2 id="expanding-your-knowledge-advanced-segment-tree-concepts"&gt;Expanding Your Knowledge: Advanced Segment Tree Concepts&lt;/h2&gt;
&lt;p&gt;Once you have a firm grasp of the basic Segment Tree operations, you can explore more advanced concepts that extend its capabilities:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Lazy Propagation Segment Trees:&lt;/strong&gt; This is a crucial extension that allows for efficient &lt;strong&gt;range updates&lt;/strong&gt; (e.g., "add X to all elements in range &lt;code&gt;[L, R]&lt;/code&gt;" or "set all elements in range &lt;code&gt;[L, R]&lt;/code&gt; to X"). Instead of updating every single node in the range, changes are "lazily" propagated down the tree only when necessary. This maintains &lt;code&gt;O(log N)&lt;/code&gt; complexity for range updates.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Persistent Segment Trees:&lt;/strong&gt; These data structures allow you to query previous versions of the tree after updates. Each update creates a new version of the tree without destroying previous ones. This is achieved by creating new nodes only on the path from the updated leaf to the root, sharing unchanged subtrees with previous versions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Merge Sort Trees:&lt;/strong&gt; Essentially a Segment Tree where each node stores a sorted list (or another Segment Tree/Fenwick Tree) of elements within its range. They are powerful for answering queries like "count elements less than X in range &lt;code&gt;[L, R]&lt;/code&gt;" or "find k-th smallest element in range &lt;code&gt;[L, R]&lt;/code&gt;".&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Segment Trees with Custom Operations:&lt;/strong&gt; The core structure is adaptable. Instead of sum, you could implement Segment Trees for GCD (Greatest Common Divisor), LCM (Least Common Multiple), matrix multiplication, or even more complex associative operations. The key is that the operation &lt;code&gt;op(a, op(b, c))&lt;/code&gt; must be equivalent to &lt;code&gt;op(op(a, b), c)&lt;/code&gt; (associativity).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These advanced topics build directly on the fundamental Segment Tree, showcasing its versatility and power in solving highly complex algorithmic challenges, often requiring a mastery of various techniques, much like solving advanced problems such as &lt;a href="/leetcode-127-word-ladder-bfs-tutorial/"&gt;Leetcode 127 Word Ladder&lt;/a&gt; which leverages BFS.&lt;/p&gt;
&lt;h2 id="conclusion-mastering-segment-trees-for-data-efficiency"&gt;Conclusion: Mastering Segment Trees for Data Efficiency&lt;/h2&gt;
&lt;p&gt;The journey through understanding and implementing the &lt;strong&gt;Segment Tree in Python, Java &amp;amp; C++&lt;/strong&gt; reveals a data structure of immense power and flexibility. We've explored its hierarchical nature, its core operations—building, querying, and updating—each performed with impressive logarithmic time complexity, making it far superior to naive approaches for dynamic range problems. From the elegant recursive structure to the practical code examples in Python, Java, and C++, you now possess a comprehensive guide to deploy this tool effectively.&lt;/p&gt;
&lt;p&gt;Mastering Segment Trees is more than just learning another algorithm; it's about developing an intuitive understanding of how to decompose complex problems into manageable subproblems and leverage hierarchical structures for optimal performance. Whether you're navigating the competitive programming landscape, designing high-performance data processing systems, or simply aiming to deepen your algorithmic knowledge, the Segment Tree is an indispensable asset. Continue practicing, experiment with different aggregate operations (min, max, GCD), and consider diving into advanced topics like Lazy Propagation to truly unlock its full potential. The efficiency and versatility it offers will undoubtedly prove invaluable in your future coding endeavors.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the primary advantage of a Segment Tree over a prefix sum array?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A Segment Tree excels in scenarios requiring both efficient range queries and point updates. While a prefix sum array offers O(1) range queries, a single element update requires rebuilding the entire prefix sum array, resulting in O(N) complexity. Segment Trees handle both operations in O(log N) time.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Can a Segment Tree be used for operations other than sum, like minimum or maximum?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Absolutely! Segment Trees are highly versatile. By simply changing the aggregation logic when building and querying (e.g., using &lt;code&gt;Math.min()&lt;/code&gt; or &lt;code&gt;std::min&lt;/code&gt; instead of &lt;code&gt;+&lt;/code&gt;), they can efficiently find range minimum, maximum, GCD, or any other associative operation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is "Lazy Propagation" in the context of Segment Trees?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Lazy Propagation is an optimization technique used with Segment Trees to handle range updates efficiently. Instead of updating every affected node in a range immediately, the updates are "marked" or "deferred" (made "lazy") on parent nodes and only propagated to children when their segments are directly involved in a query or another update. This maintains O(log N) complexity for range updates.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Segment_tree"&gt;Wikipedia: Segment Tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/segment-tree-set-1-sum-of-given-range/"&gt;GeeksforGeeks: Segment Tree | Set 1 (Sum of given range)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.topcoder.com/thrive/articles/Segment%20Tree"&gt;TopCoder Tutorial: Segment Tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://cp-algorithms.com/data_structures/segment_tree.html"&gt;CP-Algorithms: Segment Tree&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="Java"/><category term="C Plus Plus"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/segment-tree-tutorial-python-java-cpp-hero.webp" width="1200"/><media:title type="plain">Segment Tree in Python, Java &amp; C++: A Comprehensive Guide</media:title><media:description type="plain">Master the Segment Tree data structure in Python, Java, and C++ with this comprehensive guide. Learn its operations, applications, and efficient implementations.</media:description></entry><entry><title>Dijkstra Algorithm in Python, C++, Java: A Comprehensive Guide</title><link href="https://analyticsdrive.tech/dijkstra-algorithm-python-cpp-java-tutorial/" rel="alternate"/><published>2026-02-26T15:15:00+05:30</published><updated>2026-04-21T04:43:51.356438+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-26:/dijkstra-algorithm-python-cpp-java-tutorial/</id><summary type="html">&lt;p&gt;Master the Dijkstra Algorithm in Python, C++, and Java with this comprehensive guide. Learn its principles, step-by-step implementation, and real-world applications.&lt;/p&gt;</summary><content type="html">&lt;p&gt;The realm of graph theory is vast, and within it, finding the shortest path between two points is a fundamental problem with countless applications. From GPS navigation systems to network routing protocols, efficient shortest path algorithms are crucial. Among these, the &lt;strong&gt;Dijkstra Algorithm&lt;/strong&gt; stands out as a classic, renowned for its elegance and effectiveness in solving the single-source shortest path problem for graphs with non-negative edge weights. This &lt;strong&gt;comprehensive guide&lt;/strong&gt; will walk you through understanding its core principles and implementing the &lt;strong&gt;Dijkstra Algorithm in Python, C++, and Java&lt;/strong&gt;, equipping you with practical skills in these popular programming languages.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#introduction-to-dijkstras-algorithm"&gt;Introduction to Dijkstra's Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-understanding-dijkstras-algorithm"&gt;Prerequisites for Understanding Dijkstra's Algorithm&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#graphs-and-their-components"&gt;Graphs and Their Components&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#priority-queues"&gt;Priority Queues&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#basic-programming-concepts"&gt;Basic Programming Concepts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#what-is-dijkstras-algorithm-a-conceptual-deep-dive"&gt;What is Dijkstra's Algorithm? A Conceptual Deep Dive&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#how-dijkstras-algorithm-works-step-by-step-logic"&gt;How Dijkstra's Algorithm Works: Step-by-Step Logic&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-initialize-distances-and-structures"&gt;1. Initialize Distances and Structures&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-process-nodes-using-the-priority-queue"&gt;2. Process Nodes Using the Priority Queue&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-check-for-visited-nodes"&gt;3. Check for Visited Nodes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-mark-node-as-visited"&gt;4. Mark Node as Visited&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-explore-neighbors-and-update-distances-relaxation"&gt;5. Explore Neighbors and Update Distances (Relaxation)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6-repeat-until-completion"&gt;6. Repeat Until Completion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#dijkstras-algorithm-implementation-in-python"&gt;Dijkstra's Algorithm Implementation in Python&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-graph-representation"&gt;1. Graph Representation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-using-pythons-heapq-for-priority-queue"&gt;2. Using Python's heapq for Priority Queue&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-full-code-for-dijkstras-algorithm-in-python"&gt;3. Full Code for Dijkstra's Algorithm in Python&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#dijkstras-algorithm-implementation-in-c"&gt;Dijkstra's Algorithm Implementation in C++&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-graph-representation_1"&gt;1. Graph Representation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-using-stdpriority_queue"&gt;2. Using std::priority_queue&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-full-code-for-dijkstras-algorithm-in-c"&gt;3. Full Code for Dijkstra's Algorithm in C++&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#dijkstras-algorithm-implementation-in-java"&gt;Dijkstra's Algorithm Implementation in Java&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-graph-representation_2"&gt;1. Graph Representation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-using-javas-priorityqueue"&gt;2. Using Java's PriorityQueue&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-full-code-for-dijkstras-algorithm-in-java"&gt;3. Full Code for Dijkstra's Algorithm in Java&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-of-dijkstras-algorithm"&gt;Time and Space Complexity of Dijkstra's Algorithm&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-considerations"&gt;Common Mistakes and Considerations&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-negative-edge-weights"&gt;1. Negative Edge Weights&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-disconnected-graphs"&gt;2. Disconnected Graphs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-graph-representation-efficiency"&gt;3. Graph Representation Efficiency&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-priority-queue-implementation"&gt;4. Priority Queue Implementation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-handling-duplicate-entries-in-priority-queue"&gt;5. Handling Duplicate Entries in Priority Queue&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-dijkstras-algorithm"&gt;Real-World Applications of Dijkstra's Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="introduction-to-dijkstras-algorithm"&gt;Introduction to Dijkstra's Algorithm&lt;/h2&gt;
&lt;p&gt;Dijkstra's Algorithm, named after its inventor Edsger W. Dijkstra, is a greedy algorithm designed to find the shortest paths from a single source node to all other nodes in a graph. It works by iteratively exploring the most promising unvisited node, ensuring that each step takes the locally optimal choice in the hope that it will lead to a globally optimal solution. This approach is guaranteed to find the true shortest path as long as all edge weights are non-negative. The algorithm maintains a set of visited nodes and a set of unvisited nodes, alongside an array of tentative distances from the source to every other node. It continuously selects the unvisited node with the smallest tentative distance, adds it to the visited set, and then updates the distances of its neighbors. This process continues until all nodes have been visited or all reachable nodes have been processed.&lt;/p&gt;
&lt;h2 id="prerequisites-for-understanding-dijkstras-algorithm"&gt;Prerequisites for Understanding Dijkstra's Algorithm&lt;/h2&gt;
&lt;p&gt;Before diving into the implementation details, it's beneficial to have a foundational understanding of a few key concepts. A solid grasp of these building blocks will make the logic of Dijkstra's Algorithm much clearer.&lt;/p&gt;
&lt;h3 id="graphs-and-their-components"&gt;Graphs and Their Components&lt;/h3&gt;
&lt;p&gt;A graph consists of nodes (or vertices) and edges. Edges can be directed (one-way connections) or undirected (two-way connections), and in the context of Dijkstra's, they almost always have associated weights, representing cost, distance, time, or any other metric. These weights are crucial as Dijkstra's seeks to minimize the cumulative weight along a path. Graphs can be represented programmatically using an adjacency list (more memory-efficient for sparse graphs) or an adjacency matrix (better for dense graphs). Understanding these representations is key to translating the theoretical algorithm into executable code. For other graph traversal problems, especially those on a grid or where edge weights are uniform, algorithms like Breadth-First Search (BFS) are often employed, such as when finding the shortest path of &lt;code&gt;1&lt;/code&gt;s from &lt;code&gt;0&lt;/code&gt;s in the &lt;a href="/01-matrix-problem-shortest-distance-bfs-dp-explained/"&gt;01 Matrix problem&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id="priority-queues"&gt;Priority Queues&lt;/h3&gt;
&lt;p&gt;A priority queue is an abstract data type where each element has a "priority." Elements with higher priority are served before elements with lower priority. For Dijkstra's Algorithm, a min-priority queue is essential, as it allows us to efficiently retrieve the unvisited node with the smallest known distance from the source. This ability to quickly access the minimum element is what makes Dijkstra's efficient, especially for larger graphs. Without an efficient priority queue, the algorithm's performance would degrade significantly.&lt;/p&gt;
&lt;h3 id="basic-programming-concepts"&gt;Basic Programming Concepts&lt;/h3&gt;
&lt;p&gt;Familiarity with fundamental data structures like arrays, lists, and maps (dictionaries) is important. A grasp of object-oriented programming (classes, objects) will also be helpful, especially for C++ and Java implementations, where custom data types are often used to represent edges or nodes in the priority queue. Understanding loops, conditionals, and functions/methods is also a given.&lt;/p&gt;
&lt;h2 id="what-is-dijkstras-algorithm-a-conceptual-deep-dive"&gt;What is Dijkstra's Algorithm? A Conceptual Deep Dive&lt;/h2&gt;
&lt;p&gt;At its core, Dijkstra's Algorithm is a systematic way to explore a graph to find the cheapest path from a starting point to all other reachable points. Imagine you're trying to find the quickest route from your home to several friends' houses. You start by assuming the time to reach any friend is infinite, except for your own house, which takes zero time.&lt;/p&gt;
&lt;p&gt;The algorithm uses three main pieces of information:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Distances&lt;/strong&gt;: An array or map that stores the shortest known distance from the source node to every other node. Initially, the source node's distance is 0, and all other nodes have an infinite distance. This array is continuously updated as shorter paths are discovered.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visited Set&lt;/strong&gt;: A set of nodes for which the shortest path from the source has already been finalized. Once a node is added to this set, its distance is considered final and will not be updated again. This is crucial for the algorithm's correctness, preventing redundant processing and ensuring optimality.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Priority Queue&lt;/strong&gt;: A min-priority queue that stores pairs of &lt;code&gt;(distance, node)&lt;/code&gt;. This allows the algorithm to always extract the unvisited node that currently has the smallest tentative distance, making the algorithm greedy. The "greedy" aspect comes from always picking the currently shortest path, believing it will lead to the overall shortest path because edge weights are non-negative.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The beauty of Dijkstra's lies in its greedy approach. By always picking the unvisited node with the smallest current distance, the algorithm ensures that once a node is processed and added to the &lt;code&gt;visited&lt;/code&gt; set, its path from the source is indeed the shortest. This holds true because all edge weights are non-negative; adding any additional edges to an already finalized path segment would only increase the path length, never decrease it. This guarantee is fundamental to Dijkstra's correctness.&lt;/p&gt;
&lt;h2 id="how-dijkstras-algorithm-works-step-by-step-logic"&gt;How Dijkstra's Algorithm Works: Step-by-Step Logic&lt;/h2&gt;
&lt;p&gt;Let's break down the execution flow of the algorithm into digestible steps:&lt;/p&gt;
&lt;h3 id="1-initialize-distances-and-structures"&gt;1. Initialize Distances and Structures&lt;/h3&gt;
&lt;p&gt;Create a &lt;code&gt;distance&lt;/code&gt; map (or array) where &lt;code&gt;distance[source_node] = 0&lt;/code&gt; and &lt;code&gt;distance[other_nodes] = infinity&lt;/code&gt;. Also, initialize a &lt;code&gt;priority_queue&lt;/code&gt; and add the &lt;code&gt;(0, source_node)&lt;/code&gt; pair to it. Keep track of &lt;code&gt;visited&lt;/code&gt; nodes, initially an empty set or boolean array. This setup establishes the initial conditions before exploration begins.&lt;/p&gt;
&lt;h3 id="2-process-nodes-using-the-priority-queue"&gt;2. Process Nodes Using the Priority Queue&lt;/h3&gt;
&lt;p&gt;While the &lt;code&gt;priority_queue&lt;/code&gt; is not empty, extract the node &lt;code&gt;u&lt;/code&gt; with the smallest &lt;code&gt;distance&lt;/code&gt; value. This is the core greedy step where the algorithm decides which node to explore next. The priority queue efficiently provides this node, ensuring we always expand from the closest unvisited node.&lt;/p&gt;
&lt;h3 id="3-check-for-visited-nodes"&gt;3. Check for Visited Nodes&lt;/h3&gt;
&lt;p&gt;If &lt;code&gt;u&lt;/code&gt; has already been visited, skip it. This check is necessary because a node might be added to the priority queue multiple times with different (but always non-increasing) distances as new, shorter paths to it are discovered. We only care about the first time we finalize its shortest path.&lt;/p&gt;
&lt;h3 id="4-mark-node-as-visited"&gt;4. Mark Node as Visited&lt;/h3&gt;
&lt;p&gt;Mark node &lt;code&gt;u&lt;/code&gt; as visited. Its &lt;code&gt;distance[u]&lt;/code&gt; is now finalized as the shortest path from the source. At this point, no other path through an unvisited node could possibly be shorter due to the non-negative edge weight constraint.&lt;/p&gt;
&lt;h3 id="5-explore-neighbors-and-update-distances-relaxation"&gt;5. Explore Neighbors and Update Distances (Relaxation)&lt;/h3&gt;
&lt;p&gt;For each neighbor &lt;code&gt;v&lt;/code&gt; of node &lt;code&gt;u&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;*   Calculate the `new_distance = distance[u] + weight(u, v)`. This represents the path distance from the source to `v` going through `u`.
*   If `new_distance` is less than `distance[v]`, it means we found a shorter path to `v` through `u`. This process is called &amp;quot;relaxation.&amp;quot;
*   Update `distance[v] = new_distance`.
*   Add `(new_distance, v)` to the `priority_queue`. This neighbor `v` now has an updated, potentially shorter path, making it a candidate for future processing.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="6-repeat-until-completion"&gt;6. Repeat Until Completion&lt;/h3&gt;
&lt;p&gt;Continue steps 2-5 until the &lt;code&gt;priority_queue&lt;/code&gt; is empty. At this point, all reachable nodes will have had their shortest paths finalized, and the &lt;code&gt;distance&lt;/code&gt; map will contain the shortest path distances from the source to all reachable nodes.&lt;/p&gt;
&lt;h2 id="dijkstras-algorithm-implementation-in-python"&gt;Dijkstra's Algorithm Implementation in Python&lt;/h2&gt;
&lt;p&gt;Python's flexibility and built-in data structures make implementing Dijkstra's relatively straightforward. We'll use a dictionary to represent the graph as an adjacency list and Python's &lt;code&gt;heapq&lt;/code&gt; module for the priority queue.&lt;/p&gt;
&lt;h3 id="1-graph-representation"&gt;1. Graph Representation&lt;/h3&gt;
&lt;p&gt;In Python, an adjacency list can be represented using a dictionary where keys are nodes and values are lists of &lt;code&gt;(neighbor, weight)&lt;/code&gt; tuples.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;graph&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&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;h3 id="2-using-pythons-heapq-for-priority-queue"&gt;2. Using Python's &lt;code&gt;heapq&lt;/code&gt; for Priority Queue&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;heapq&lt;/code&gt; module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. It allows us to push and pop elements efficiently. Since &lt;code&gt;heapq&lt;/code&gt; is a min-heap, it's perfect for our needs. We'll store tuples &lt;code&gt;(distance, node)&lt;/code&gt; in the heap, and it will automatically prioritize by the first element (distance).&lt;/p&gt;
&lt;h3 id="3-full-code-for-dijkstras-algorithm-in-python"&gt;3. Full Code for Dijkstra's Algorithm in Python&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;heapq&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;dijkstra_python&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start_node&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="sd"&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
&lt;span class="sd"&gt;    Implements Dijkstra&amp;#39;s Algorithm to find the shortest paths&lt;/span&gt;
&lt;span class="sd"&gt;    from a start_node to all other nodes in a graph.&lt;/span&gt;

&lt;span class="sd"&gt;    Args:&lt;/span&gt;
&lt;span class="sd"&gt;        graph (dict): Adjacency list representation of the graph.&lt;/span&gt;
&lt;span class="sd"&gt;                      e.g., {&amp;#39;A&amp;#39;: [(&amp;#39;B&amp;#39;, 1), (&amp;#39;C&amp;#39;, 4)], ...}&lt;/span&gt;
&lt;span class="sd"&gt;        start_node (str): The starting node for the algorithm.&lt;/span&gt;

&lt;span class="sd"&gt;    Returns:&lt;/span&gt;
&lt;span class="sd"&gt;        dict: A dictionary mapping each node to its shortest distance&lt;/span&gt;
&lt;span class="sd"&gt;              from the start_node. Returns float(&amp;#39;inf&amp;#39;) for unreachable nodes.&lt;/span&gt;
&lt;span class="sd"&gt;    &amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;
    &lt;span class="c1"&gt;# Step 1: Initialize distances and structures&lt;/span&gt;
    &lt;span class="n"&gt;distances&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;inf&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start_node&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

    &lt;span class="c1"&gt;# Priority queue stores (distance, node) tuples&lt;/span&gt;
    &lt;span class="n"&gt;priority_queue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start_node&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;

    &lt;span class="c1"&gt;# Keep track of visited nodes to avoid redundant processing&lt;/span&gt;
    &lt;span class="n"&gt;visited&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

    &lt;span class="c1"&gt;# Step 2: Process nodes using the priority queue&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;priority_queue&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Extract the node with the smallest distance&lt;/span&gt;
        &lt;span class="n"&gt;current_distance&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;current_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;priority_queue&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 3: Check for visited nodes&lt;/span&gt;
        &lt;span class="c1"&gt;# If we&amp;#39;ve already found the shortest path to this node, skip it&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current_node&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;continue&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 4: Mark node as visited&lt;/span&gt;
        &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current_node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 5: Explore neighbors and update distances (Relaxation)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;weight&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current_node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[]):&lt;/span&gt;
            &lt;span class="c1"&gt;# Only consider unvisited neighbors for relaxation&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;neighbor&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;distance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current_distance&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;weight&lt;/span&gt;
                &lt;span class="c1"&gt;# If a shorter path to the neighbor is found&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;distance&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                    &lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;distance&lt;/span&gt;
                    &lt;span class="c1"&gt;# Add/update neighbor in the priority queue&lt;/span&gt;
                    &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;priority_queue&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;distance&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

    &lt;span class="c1"&gt;# Step 6: Return the final distances&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;distances&lt;/span&gt;

&lt;span class="c1"&gt;# Step 7: Example Usage&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="vm"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;__main__&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;example_graph&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;F&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;F&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="n"&gt;start_node_py&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;
    &lt;span class="n"&gt;shortest_paths_py&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dijkstra_python&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;example_graph&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start_node_py&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Dijkstra&amp;#39;s Algorithm in Python (starting from &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;start_node_py&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;):&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;shortest_paths_py&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;  Shortest path from &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;start_node_py&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt; to &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Example with a disconnected node&lt;/span&gt;
    &lt;span class="n"&gt;disconnected_graph&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)],&lt;/span&gt;
        &lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;Dijkstra&amp;#39;s Algorithm in Python (disconnected graph, starting from A):&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;disconnected_paths&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dijkstra_python&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;disconnected_graph&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;disconnected_paths&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;  Shortest path from A to &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This Python implementation provides a clear, concise, and efficient way to compute the shortest paths using Dijkstra's algorithm. The use of &lt;code&gt;heapq&lt;/code&gt; streamlines the priority queue operations, making the code quite readable.&lt;/p&gt;
&lt;h2 id="dijkstras-algorithm-implementation-in-c"&gt;Dijkstra's Algorithm Implementation in C++&lt;/h2&gt;
&lt;p&gt;C++ offers powerful standard library containers and algorithms, making it an excellent choice for implementing graph algorithms. We'll use &lt;code&gt;std::vector&lt;/code&gt; for adjacency lists, &lt;code&gt;std::priority_queue&lt;/code&gt; for the priority queue, and &lt;code&gt;std::vector&lt;/code&gt; for distances and tracking.&lt;/p&gt;
&lt;h3 id="1-graph-representation_1"&gt;1. Graph Representation&lt;/h3&gt;
&lt;p&gt;In C++, an adjacency list can be represented as &lt;code&gt;std::vector&amp;lt;std::vector&amp;lt;std::pair&amp;lt;int, int&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt;. Each inner vector stores pairs of &lt;code&gt;(neighbor_node, weight)&lt;/code&gt;. We'll typically map node names (e.g., characters) to integer indices for easier array/vector access.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;// Example graph representation for 5 nodes (0-4)&lt;/span&gt;
&lt;span class="c1"&gt;// Node 0: (Neighbor 1, Weight 1), (Neighbor 2, Weight 4)&lt;/span&gt;
&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;pair&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;// To populate:&lt;/span&gt;
&lt;span class="c1"&gt;// adj[0].push_back({1, 1});&lt;/span&gt;
&lt;span class="c1"&gt;// adj[0].push_back({2, 4});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="2-using-stdpriority_queue"&gt;2. Using &lt;code&gt;std::priority_queue&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;C++'s &lt;code&gt;std::priority_queue&lt;/code&gt; is a max-heap by default. To make it a min-heap for &lt;code&gt;(distance, node)&lt;/code&gt; pairs, we can store &lt;code&gt;(negative_distance, node)&lt;/code&gt; or use a custom comparator. A common trick for min-heap behavior with pairs is to store &lt;code&gt;std::pair&amp;lt;int, int&amp;gt;&lt;/code&gt; as &lt;code&gt;(distance, node)&lt;/code&gt; and use &lt;code&gt;std::greater&amp;lt;std::pair&amp;lt;int, int&amp;gt;&amp;gt;&lt;/code&gt; as the comparator, or simply store &lt;code&gt;(-distance, node)&lt;/code&gt; and extract the max. We will use the &lt;code&gt;std::greater&lt;/code&gt; trick, which naturally orders pairs by their first element in ascending order.&lt;/p&gt;
&lt;h3 id="3-full-code-for-dijkstras-algorithm-in-c"&gt;3. Full Code for Dijkstra's Algorithm in C++&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;queue&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt;      // For std::priority_queue&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;limits&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt;     // For std::numeric_limits&amp;lt;int&amp;gt;::max()&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;map&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt;        // For mapping char nodes to int indices&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;tuple&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt;      // For std::tuple in example usage&lt;/span&gt;

&lt;span class="c1"&gt;// Define a struct to hold edge information&lt;/span&gt;
&lt;span class="k"&gt;struct&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;// Define a struct for nodes in the priority queue&lt;/span&gt;
&lt;span class="c1"&gt;// The first element is distance, second is node index&lt;/span&gt;
&lt;span class="k"&gt;struct&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;NodeDist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Custom comparator for min-priority queue&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// This makes std::priority_queue act as a min-heap for NodeDist objects&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;operator&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;dijkstra_cpp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start_node_idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;num_nodes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Step 1: Initialize distances and structures&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num_nodes&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;numeric_limits&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;::&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start_node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Min-priority queue: stores {distance, node_index}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;priority_queue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;greater&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start_node_idx&lt;/span&gt;&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// An explicit &amp;#39;visited&amp;#39; set/array can also be used, but checking&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// `current_distance &amp;gt; distances[current_node_idx]` upon extraction&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// is a common and valid way to handle redundant entries in the PQ.&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Step 2: Process nodes using the priority queue&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;top&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current_distance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current_node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;node_idx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 3: Check if this path is already longer than a known shortest path&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If we extracted a node with a distance greater than what&amp;#39;s already known&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// (due to a previous shorter path being found and added to PQ), skip it.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// This effectively handles &amp;quot;visited&amp;quot; nodes or redundant entries.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current_distance&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;current_node_idx&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 4: No explicit mark as visited needed here due to the check above.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Conceptually, distances[current_node_idx] is now finalized.&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 5: Explore neighbors and update distances (Relaxation)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;current_node_idx&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighbor_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Calculate new distance to neighbor through current_node&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;current_node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;numeric_limits&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;::&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Ensure current_node is reachable&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;current_node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;neighbor_idx&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;neighbor_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;current_node_idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;neighbor_idx&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighbor_idx&lt;/span&gt;&lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Step 6: Print results&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Dijkstra&amp;#39;s Algorithm in C++ (starting from node &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start_node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;):&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;num_nodes&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;  Shortest path from &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start_node_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; to &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;numeric_limits&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;::&lt;/span&gt;&lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Unreachable&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Step 7: Example Usage&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Map char nodes to int indices for easier use with vector&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_to_idx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idx_to_node&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// To map back from index to char for printing&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;next_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;get_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="p"&gt;](&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_char&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node_to_idx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node_char&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_to_idx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;node_to_idx&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_char&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;next_idx&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;idx_to_node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node_char&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_to_idx&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node_char&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Define graph edges&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;tuple&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;F&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;F&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Populate node indices and determine total number of nodes&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge_tuple&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;get_idx&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge_tuple&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;get_idx&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge_tuple&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;num_nodes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;next_idx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Create adjacency list&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num_nodes&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge_tuple&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;get_idx&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge_tuple&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v_idx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;get_idx&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge_tuple&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge_tuple&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u_idx&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="n"&gt;v_idx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start_node_char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start_node_idx_cpp&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node_to_idx&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start_node_char&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;dijkstra_cpp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;start_node_idx_cpp&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;num_nodes&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&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;The C++ implementation is more verbose due to explicit memory management, types, and the need for custom comparators for &lt;code&gt;std::priority_queue&lt;/code&gt;. However, it offers high performance and fine-grained control, which are often critical in large-scale applications. Note the use of &lt;code&gt;std::numeric_limits&amp;lt;int&amp;gt;::max()&lt;/code&gt; for infinity and the &lt;code&gt;NodeDist&lt;/code&gt; struct with overloaded &lt;code&gt;operator&amp;gt;&lt;/code&gt; for the priority queue.&lt;/p&gt;
&lt;h2 id="dijkstras-algorithm-implementation-in-java"&gt;Dijkstra's Algorithm Implementation in Java&lt;/h2&gt;
&lt;p&gt;Java's robust ecosystem and object-oriented nature make it well-suited for implementing graph algorithms. We'll leverage &lt;code&gt;ArrayList&lt;/code&gt; for adjacency lists, &lt;code&gt;PriorityQueue&lt;/code&gt; for the priority queue, and arrays for distances and visited status.&lt;/p&gt;
&lt;h3 id="1-graph-representation_2"&gt;1. Graph Representation&lt;/h3&gt;
&lt;p&gt;In Java, an adjacency list can be represented as &lt;code&gt;ArrayList&amp;lt;ArrayList&amp;lt;Edge&amp;gt;&amp;gt;&lt;/code&gt; or &lt;code&gt;HashMap&amp;lt;Integer, ArrayList&amp;lt;Edge&amp;gt;&amp;gt;&lt;/code&gt;. A custom &lt;code&gt;Edge&lt;/code&gt; class or a &lt;code&gt;Pair&lt;/code&gt; class for &lt;code&gt;(neighbor, weight)&lt;/code&gt; is typically used.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="c1"&gt;// Example for 5 nodes (0-4)&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;to&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="c1"&gt;// To populate:&lt;/span&gt;
&lt;span class="c1"&gt;// adj.get(0).add(new Edge(1, 1));&lt;/span&gt;
&lt;span class="c1"&gt;// adj.get(0).add(new Edge(2, 4));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="2-using-javas-priorityqueue"&gt;2. Using Java's &lt;code&gt;PriorityQueue&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Java's &lt;code&gt;java.util.PriorityQueue&lt;/code&gt; is a min-priority queue by default for objects that implement &lt;code&gt;Comparable&lt;/code&gt; or are constructed with a &lt;code&gt;Comparator&lt;/code&gt;. We'll define a &lt;code&gt;NodeDist&lt;/code&gt; class (or similar) to store &lt;code&gt;(distance, node_index)&lt;/code&gt; and implement &lt;code&gt;Comparable&lt;/code&gt; to prioritize by distance.&lt;/p&gt;
&lt;h3 id="3-full-code-for-dijkstras-algorithm-in-java"&gt;3. Full Code for Dijkstra's Algorithm in Java&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.*&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.function.Function&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// For the lambda in main example&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DijkstraJava&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Helper class to represent an edge in the graph&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;to&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Helper class for nodes in the priority queue&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Stores (distance, node_index) and implements Comparable for min-priority queue&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;NodeDist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;implements&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Comparable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;NodeDist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;dist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;nodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeIdx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Compare by distance for min-priority queue behavior&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="nd"&gt;@Override&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;compareTo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;compare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;dijkstra_java&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numNodes&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;startNodeIdx&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 1: Initialize distances and structures&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;numNodes&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;fill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;MAX_VALUE&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Represents infinity&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;startNodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Min-priority queue: stores {distance, node_index}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;PriorityQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;PriorityQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;startNodeIdx&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Boolean array to keep track of visited nodes.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// This helps avoid reprocessing nodes whose shortest path is already finalized.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;numNodes&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 2: Process nodes using the priority queue&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isEmpty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;poll&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Get node with smallest distance&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentDist&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;currentNodeIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;nodeIdx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Step 3: Check for visited nodes or redundant entries&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// If we&amp;#39;ve already found a shorter path to this node, or processed it, skip it.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;currentNodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Step 4: Mark node as visited&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;currentNodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Step 5: Explore neighbors and update distances (Relaxation)&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;currentNodeIdx&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighborIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;to&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;neighborIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Only consider unvisited neighbors for relaxation&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;currentNodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;MAX_VALUE&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Ensure current_node is reachable&lt;/span&gt;
&lt;span class="w"&gt;                        &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;currentNodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;neighborIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                        &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;neighborIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;currentNodeIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                        &lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;NodeDist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;neighborIdx&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighborIdx&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 6: Return the final distances array&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;distances&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Step 7: Example Usage&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// We&amp;#39;ll use character mapping like C++ example for clarity&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeToIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idxToNode&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// To map back from index to char for printing&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nextIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Helper to get integer index for a char node, creating new if not exists&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Function&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;getIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nodeChar&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;nodeToIdx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;containsKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nodeChar&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;nodeToIdx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nodeChar&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nextIdx&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;idxToNode&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nodeChar&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeToIdx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nodeChar&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Define graph edges as tuples (source_char, dest_char, weight)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;asList&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;F&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)),&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;F&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Populate node indices and determine total number of nodes&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;getIdx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;apply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getKey&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;getIdx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;apply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getValue&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="na"&gt;getKey&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numNodes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nextIdx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Create adjacency list&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numNodes&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numNodes&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;AbstractMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SimpleEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edges&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;uIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;getIdx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;apply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getKey&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;vIdx&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;getIdx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;apply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getValue&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="na"&gt;getKey&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;edge&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getValue&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="na"&gt;getValue&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;uIdx&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Edge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vIdx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;weight&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;startNodeChar&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="sc"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;startNodeIdxJava&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;nodeToIdx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;startNodeChar&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;shortestPathsJava&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dijkstra_java&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numNodes&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;startNodeIdxJava&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Dijkstra&amp;#39;s Algorithm in Java (starting from &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;startNodeChar&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;):&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numNodes&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;  Shortest path from &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;startNodeChar&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; to &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;idxToNode&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shortestPathsJava&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;MAX_VALUE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Unreachable&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shortestPathsJava&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &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;The Java implementation mirrors the C++ logic but uses Java's object-oriented features more prominently for defining &lt;code&gt;Edge&lt;/code&gt; and &lt;code&gt;NodeDist&lt;/code&gt; classes. The &lt;code&gt;Comparable&lt;/code&gt; interface is crucial for &lt;code&gt;PriorityQueue&lt;/code&gt; to correctly order elements.&lt;/p&gt;
&lt;h2 id="time-and-space-complexity-of-dijkstras-algorithm"&gt;Time and Space Complexity of Dijkstra's Algorithm&lt;/h2&gt;
&lt;p&gt;Understanding the efficiency of Dijkstra's Algorithm is crucial for choosing the right tool for the job. Its complexity depends heavily on the graph representation and the priority queue implementation. Let &lt;code&gt;V&lt;/code&gt; be the number of vertices (nodes) and &lt;code&gt;E&lt;/code&gt; be the number of edges.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Without a Priority Queue&lt;/strong&gt;: If the algorithm uses a simple array or list to find the minimum distance node in each step, iterating through all unvisited nodes to find the minimum would take &lt;code&gt;O(V)&lt;/code&gt; time. Since there are &lt;code&gt;V&lt;/code&gt; nodes, this search is performed &lt;code&gt;V&lt;/code&gt; times, leading to a total time complexity of &lt;code&gt;O(V^2)&lt;/code&gt;. This approach is generally less efficient but can be acceptable for very dense graphs where &lt;code&gt;E&lt;/code&gt; is close to &lt;code&gt;V^2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;With a Binary Heap (Priority Queue)&lt;/strong&gt;: This is the most common and efficient implementation for general graphs.&lt;ul&gt;
&lt;li&gt;Extracting the minimum element from the priority queue takes &lt;code&gt;O(log V)&lt;/code&gt; time. This operation occurs &lt;code&gt;V&lt;/code&gt; times (once for each node when its shortest path is finalized).&lt;/li&gt;
&lt;li&gt;Updating the distance of a neighbor (a "decrease-key" operation, which typically involves removing and re-inserting in a binary heap) and adding it to the priority queue also takes &lt;code&gt;O(log V)&lt;/code&gt; time. In the worst case, every edge &lt;code&gt;E&lt;/code&gt; might cause a priority queue insertion or update.&lt;/li&gt;
&lt;li&gt;Therefore, the total time complexity is &lt;code&gt;O(E log V + V log V)&lt;/code&gt;, which simplifies to &lt;code&gt;O(E log V)&lt;/code&gt; since &lt;code&gt;E&lt;/code&gt; is typically greater than or equal to &lt;code&gt;V-1&lt;/code&gt; for a connected graph. For sparse graphs (where &lt;code&gt;E&lt;/code&gt; is much smaller than &lt;code&gt;V^2&lt;/code&gt;), this is significantly better than &lt;code&gt;O(V^2)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;With a Fibonacci Heap&lt;/strong&gt;: A more advanced priority queue, a Fibonacci heap, can further optimize the "decrease-key" operation to an amortized &lt;code&gt;O(1)&lt;/code&gt;. This leads to a theoretical time complexity of &lt;code&gt;O(E + V log V)&lt;/code&gt;. However, Fibonacci heaps are notoriously complex to implement, and their constant factors are often large, making binary heaps usually preferred in practice unless &lt;code&gt;E&lt;/code&gt; is exceedingly large compared to &lt;code&gt;V&lt;/code&gt;, where the theoretical advantage might outweigh implementation complexity.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;The space complexity is &lt;code&gt;O(V + E)&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;&lt;code&gt;O(V)&lt;/code&gt; for storing distances (e.g., in an array or map) and &lt;code&gt;O(V)&lt;/code&gt; for the visited status.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;O(V + E)&lt;/code&gt; for the adjacency list representation of the graph itself.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;O(V)&lt;/code&gt; for the priority queue in the worst case (when all nodes are in the queue simultaneously, such as in a star graph).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="common-mistakes-and-considerations"&gt;Common Mistakes and Considerations&lt;/h2&gt;
&lt;p&gt;While Dijkstra's Algorithm is powerful, it comes with specific limitations and common pitfalls that developers must be aware of to ensure correct and efficient usage.&lt;/p&gt;
&lt;h3 id="1-negative-edge-weights"&gt;1. Negative Edge Weights&lt;/h3&gt;
&lt;p&gt;Dijkstra's Algorithm &lt;strong&gt;does not work correctly with negative edge weights&lt;/strong&gt;. Its greedy approach assumes that once a node's distance is finalized and added to the &lt;code&gt;visited&lt;/code&gt; set, it cannot be improved further. However, a negative edge originating from an already visited node could potentially reduce the path to an unvisited neighbor, and subsequently, through that neighbor, to other nodes, including those that were supposedly "finalized." This violates the core assumption of Dijkstra's. For graphs with negative weights (but no negative cycles), algorithms like Bellman-Ford or SPFA are appropriate. For unweighted graphs, a simpler approach like &lt;a href="/leetcode-127-word-ladder-bfs-tutorial/"&gt;Breadth-First Search (BFS)&lt;/a&gt; can suffice to find the shortest path.&lt;/p&gt;
&lt;h3 id="2-disconnected-graphs"&gt;2. Disconnected Graphs&lt;/h3&gt;
&lt;p&gt;If the graph contains disconnected components, Dijkstra's Algorithm will only find shortest paths to nodes within the component reachable from the source node. Nodes in other components will retain their initial "infinity" distance. The provided implementations correctly handle this by leaving unreachable nodes with &lt;code&gt;float('inf')&lt;/code&gt; or &lt;code&gt;Integer.MAX_VALUE&lt;/code&gt;. It's important to interpret these "infinity" values correctly in the results.&lt;/p&gt;
&lt;h3 id="3-graph-representation-efficiency"&gt;3. Graph Representation Efficiency&lt;/h3&gt;
&lt;p&gt;Choosing an efficient graph representation is crucial for performance. For sparse graphs (where &lt;code&gt;E &amp;lt;&amp;lt; V^2&lt;/code&gt;), an adjacency list is significantly more memory and time-efficient than an adjacency matrix. For very dense graphs, an adjacency matrix might be competitive in terms of &lt;code&gt;O(V^2)&lt;/code&gt; complexity, but typically, adjacency lists combined with priority queues offer better asymptotic performance.&lt;/p&gt;
&lt;h3 id="4-priority-queue-implementation"&gt;4. Priority Queue Implementation&lt;/h3&gt;
&lt;p&gt;A poorly implemented priority queue (e.g., manually searching for the minimum in an unsorted list in each step) can degrade the time complexity from an optimal &lt;code&gt;O(E log V)&lt;/code&gt; to &lt;code&gt;O(V^2)&lt;/code&gt;. Always use optimized priority queue data structures provided by standard libraries (&lt;code&gt;heapq&lt;/code&gt; in Python, &lt;code&gt;std::priority_queue&lt;/code&gt; in C++, &lt;code&gt;java.util.PriorityQueue&lt;/code&gt; in Java) for efficient performance.&lt;/p&gt;
&lt;h3 id="5-handling-duplicate-entries-in-priority-queue"&gt;5. Handling Duplicate Entries in Priority Queue&lt;/h3&gt;
&lt;p&gt;When a node's distance is updated (i.e., a shorter path to it is found), it might be re-added to the priority queue with its new, smaller distance. This creates duplicate entries for the same node in the queue, where older entries have larger distances. The algorithm must handle these correctly. A common and efficient way is to check if &lt;code&gt;current_distance &amp;gt; distances[current_node]&lt;/code&gt; &lt;em&gt;when extracting&lt;/em&gt; from the priority queue; if true, it means a shorter path to &lt;code&gt;current_node&lt;/code&gt; has already been processed (or an even shorter path was found and is already in the &lt;code&gt;distances&lt;/code&gt; array), so the current (longer) entry can be safely skipped. Our C++ and Java examples implicitly handle this by this check, while the Python example uses an explicit &lt;code&gt;visited&lt;/code&gt; set to achieve a similar effect. Both approaches are valid.&lt;/p&gt;
&lt;h2 id="real-world-applications-of-dijkstras-algorithm"&gt;Real-World Applications of Dijkstra's Algorithm&lt;/h2&gt;
&lt;p&gt;The utility of Dijkstra's Algorithm extends far beyond academic exercises and forms the backbone of many critical systems we use daily:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;GPS Navigation and Mapping Services&lt;/strong&gt;: Every time you request directions for the shortest or fastest route between two locations, algorithms similar to Dijkstra's are at work. They calculate optimal paths on road networks where edge weights represent distances, travel times, or even traffic conditions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Network Routing Protocols&lt;/strong&gt;: In computer networks, routers use shortest path algorithms to determine the most efficient routes for data packets to travel from source to destination. OSPF (Open Shortest Path First) is a prominent example of a routing protocol that relies on Dijkstra's Algorithm to build and maintain routing tables.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Telephone Networks&lt;/strong&gt;: Used for finding the shortest path for voice and data connections, ensuring efficient call routing and data transmission.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Social Network Analysis&lt;/strong&gt;: Can be used to find the "shortest chain" of connections (or degrees of separation) between two people, which is related to the "six degrees of separation" concept. This helps in understanding influence and connectivity within networks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resource Allocation&lt;/strong&gt;: Optimizing the flow of resources in various systems, such as logistics, supply chain management, or even urban planning, where edges represent costs, capacities, or distances between resource points.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Image Processing&lt;/strong&gt;: In medical imaging and computer vision, Dijkstra's algorithm can be used for tasks like finding the "shortest path" for a cut in image segmentation algorithms, helping to delineate objects within an image.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Gaming AI&lt;/strong&gt;: Non-player characters (NPCs) in video games often use pathfinding algorithms, including variants of Dijkstra's, to navigate complex game environments efficiently to reach a destination or avoid obstacles.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: What are the main limitations of Dijkstra's Algorithm?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Dijkstra's Algorithm's primary limitation is its inability to correctly handle graphs with negative edge weights. Its greedy approach relies on the assumption that once a node's shortest path is found, it cannot be improved, an assumption violated by negative edges. Additionally, it can be less efficient than specialized algorithms for extremely sparse or dense graphs in specific scenarios.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: When should I use Dijkstra's Algorithm instead of BFS or DFS?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Use Dijkstra's Algorithm when you need to find the single-source shortest paths in a graph where edges have &lt;strong&gt;non-negative weights&lt;/strong&gt;. If the graph has &lt;strong&gt;unweighted edges&lt;/strong&gt;, Breadth-First Search (BFS) is simpler and more efficient for finding shortest paths. Depth-First Search (DFS) is typically used for traversal, cycle detection, or topological sorting, not for shortest path problems.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What data structure is crucial for an efficient Dijkstra implementation?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A &lt;strong&gt;min-priority queue&lt;/strong&gt; is crucial for an efficient Dijkstra implementation. It allows the algorithm to quickly extract the unvisited node with the smallest tentative distance from the source in &lt;code&gt;O(log V)&lt;/code&gt; time, leading to an overall time complexity of &lt;code&gt;O(E log V)&lt;/code&gt; for a graph with V vertices and E edges. Without it, the complexity can degrade to &lt;code&gt;O(V^2)&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Wikipedia - Dijkstra's Algorithm&lt;/strong&gt;: &lt;a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm"&gt;https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;GeeksforGeeks - Dijkstra's shortest path algorithm&lt;/strong&gt;: &lt;a href="https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/"&gt;https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Programiz - Dijkstra's Algorithm&lt;/strong&gt;: &lt;a href="https://www.programiz.com/dsa/dijkstra-algorithm"&gt;https://www.programiz.com/dsa/dijkstra-algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Python &lt;code&gt;heapq&lt;/code&gt; module documentation&lt;/strong&gt;: &lt;a href="https://docs.python.org/3/library/heapq.html"&gt;https://docs.python.org/3/library/heapq.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;C++ &lt;code&gt;std::priority_queue&lt;/code&gt; documentation (cppreference)&lt;/strong&gt;: &lt;a href="https://en.cppreference.com/w/cpp/container/priority_queue"&gt;https://en.cppreference.com/w/cpp/container/priority_queue&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Python"/><category term="C Plus Plus"/><category term="Problem Solving"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/dijkstra-algorithm-python-cpp-java-tutorial.webp" width="1200"/><media:title type="plain">Dijkstra Algorithm in Python, C++, Java: A Comprehensive Guide</media:title><media:description type="plain">Master the Dijkstra Algorithm in Python, C++, and Java with this comprehensive guide. Learn its principles, step-by-step implementation, and real-world applications.</media:description></entry><entry><title>Leetcode 1976: Number of Ways to Arrive at Destination Explained</title><link href="https://analyticsdrive.tech/leetcode-1976-number-of-ways-arrive-destination-tutorial/" rel="alternate"/><published>2026-02-26T15:02:00+05:30</published><updated>2026-04-21T04:43:51.514009+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-26:/leetcode-1976-number-of-ways-arrive-destination-tutorial/</id><summary type="html">&lt;p&gt;Master Leetcode 1976: Number of Ways to Arrive at Destination. This guide explains the modified Dijkstra's algorithm to solve this complex graph problem.&lt;/p&gt;</summary><content type="html">&lt;p&gt;When tackling advanced graph problems on platforms like Leetcode, you often encounter scenarios that push beyond the standard textbook algorithms. One such intriguing challenge is &lt;strong&gt;Leetcode 1976: Number of Ways to Arrive at Destination&lt;/strong&gt;. This problem asks us to find not just the shortest time to reach a specific point in a city, but also the total count of distinct paths that achieve that exact minimum travel time. This comprehensive tutorial will guide you through understanding, approaching, and implementing a solution to effectively solve this problem, ensuring you grasp the nuances of modifying classic algorithms for modern challenges. By the end of this guide, you will have a clear understanding of how to combine shortest path algorithms with dynamic programming principles to solve problems requiring the computation of multiple optimal paths.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-tackling-leetcode-1976"&gt;Prerequisites for Tackling Leetcode 1976&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#graph-theory-fundamentals"&gt;Graph Theory Fundamentals&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#dijkstras-algorithm"&gt;Dijkstra's Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#dynamic-programming-concepts"&gt;Dynamic Programming Concepts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#modular-arithmetic"&gt;Modular Arithmetic&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-leetcode-1976-number-of-ways-to-arrive-at-destination"&gt;Understanding Leetcode 1976: Number of Ways to Arrive at Destination&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-idea-and-algorithm-approach"&gt;Core Idea and Algorithm Approach&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#detailed-steps-for-solving-leetcode-1976"&gt;Detailed Steps for Solving Leetcode 1976&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-1-represent-the-graph"&gt;Step 1: Represent the Graph&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-2-initialize-data-structures"&gt;Step 2: Initialize Data Structures&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-3-implement-modified-dijkstras-algorithm"&gt;Step 3: Implement Modified Dijkstra's Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-4-return-the-result"&gt;Step 4: Return the Result&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#complete-code-implementation-python"&gt;Complete Code Implementation (Python)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#example-walkthrough"&gt;Example Walkthrough&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#complexity-analysis"&gt;Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-troubleshooting"&gt;Common Mistakes and Troubleshooting&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-incorrectly-handling-new_time-min_timev"&gt;1. Incorrectly Handling new_time == min_time[v]&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-forgetting-modular-arithmetic"&gt;2. Forgetting Modular Arithmetic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-incorrect-graph-representation"&gt;3. Incorrect Graph Representation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-initialization-errors"&gt;4. Initialization Errors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-stale-entries-in-priority-queue-less-common-with-proper-checks"&gt;5. Stale Entries in Priority Queue (Less common with proper checks)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="prerequisites-for-tackling-leetcode-1976"&gt;Prerequisites for Tackling Leetcode 1976&lt;/h2&gt;
&lt;p&gt;Before diving into the solution for "Number of Ways to Arrive at Destination," a solid understanding of several fundamental concepts is crucial. These prerequisites form the bedrock upon which our optimized algorithm will be built. Familiarity with these topics will ensure you can fully grasp the intricacies of the problem and its solution.&lt;/p&gt;
&lt;h3 id="graph-theory-fundamentals"&gt;Graph Theory Fundamentals&lt;/h3&gt;
&lt;p&gt;At its heart, this Leetcode problem is about navigating a graph. Understanding basic graph terminology is essential. For instance, correctly identifying nodes, edges, and their weights is crucial for problems involving pathfinding, much like analyzing movement in a grid-based scenario as seen in &lt;a href="/01-matrix-problem-shortest-distance-bfs-dp-explained/"&gt;Unraveling the 01 Matrix: Finding the Nearest Zero with BFS and DP&lt;/a&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Nodes (Vertices):&lt;/strong&gt; These represent the intersections or locations in our city. In Leetcode 1976, each intersection is a node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edges:&lt;/strong&gt; These represent the roads connecting the intersections. An edge connects two nodes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Weights:&lt;/strong&gt; Each edge has an associated weight, which in this problem signifies the time it takes to travel along that road. Our goal is to minimize the total travel time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Undirected Graph:&lt;/strong&gt; The problem states that roads can be traveled in both directions. This means if there's an edge from node A to node B, there's also an equivalent edge from node B to node A with the same weight. Our graph representation must account for this bidirectionality.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Adjacency List:&lt;/strong&gt; This is a common and efficient way to represent a graph, especially for sparse graphs (graphs with relatively few edges compared to the maximum possible). An adjacency list stores, for each node, a list of its neighbors and the weights of the edges connecting them.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="dijkstras-algorithm"&gt;Dijkstra's Algorithm&lt;/h3&gt;
&lt;p&gt;Dijkstra's algorithm is the cornerstone for solving the single-source shortest path problem on graphs with non-negative edge weights. It is a fundamental concept in graph theory, often applied alongside or in comparison to other graph traversal techniques like BFS for unweighted graphs, similar to problems found in &lt;a href="/leetcode-127-word-ladder-bfs-tutorial/"&gt;Leetcode 127 Word Ladder: Master the BFS Approach Easily&lt;/a&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Purpose:&lt;/strong&gt; It efficiently finds the shortest path (minimum cumulative weight) from a single source node to all other nodes in the graph.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mechanism:&lt;/strong&gt; It works by iteratively visiting nodes, always selecting the unvisited node with the smallest known distance from the source. It then relaxes all edges connected to this chosen node, updating the distances to its neighbors if a shorter path is found.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Priority Queue:&lt;/strong&gt; Dijkstra's algorithm heavily relies on a priority queue (min-heap) to efficiently retrieve the unvisited node with the smallest current distance. The priority queue stores tuples of &lt;code&gt;(distance, node)&lt;/code&gt;, ordered by &lt;code&gt;distance&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Relaxation:&lt;/strong&gt; The core operation where we check if traversing through the current node offers a shorter path to an adjacent node. If &lt;code&gt;dist[u] + weight(u, v) &amp;lt; dist[v]&lt;/code&gt;, then &lt;code&gt;dist[v]&lt;/code&gt; is updated.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;While Dijkstra's directly finds the shortest path, we need to extend it to count the number of ways to achieve that minimum time.&lt;/p&gt;
&lt;h3 id="dynamic-programming-concepts"&gt;Dynamic Programming Concepts&lt;/h3&gt;
&lt;p&gt;Dynamic programming (DP) is an algorithmic technique for solving complex problems by breaking them down into simpler subproblems. In our case, DP principles help us accumulate the count of paths. This approach of building solutions from subproblems is a versatile tool across many algorithmic challenges, including those requiring pathfinding in mazes, which can sometimes benefit from similar thought processes, as explored in guides like &lt;a href="/cses-labyrinth-problem-python-java-cpp-guide/"&gt;CSES Labyrinth Problem in Python, Java &amp;amp; C++: A Complete Guide&lt;/a&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Optimal Substructure:&lt;/strong&gt; The optimal solution to the problem can be constructed from the optimal solutions of its subproblems. If the shortest path to node &lt;code&gt;v&lt;/code&gt; passes through node &lt;code&gt;u&lt;/code&gt;, then the path from the source to &lt;code&gt;u&lt;/code&gt; must also be a shortest path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Overlapping Subproblems:&lt;/strong&gt; The same subproblems are encountered multiple times. By storing the results of these subproblems (memoization), we avoid redundant computations. Here, when we find a new path to a node that has the &lt;em&gt;same minimum time&lt;/em&gt; as a previously found path, we add the ways, rather than recalculating everything.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;State Definition:&lt;/strong&gt; For Leetcode 1976, we will maintain two critical pieces of information for each node: &lt;code&gt;min_time[node]&lt;/code&gt; (the minimum time to reach &lt;code&gt;node&lt;/code&gt; from the source) and &lt;code&gt;ways[node]&lt;/code&gt; (the number of ways to achieve &lt;code&gt;min_time[node]&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="modular-arithmetic"&gt;Modular Arithmetic&lt;/h3&gt;
&lt;p&gt;The problem statement often specifies that the "number of ways" can be very large, so we should return the result modulo &lt;code&gt;10^9 + 7&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Why Modulo?&lt;/strong&gt; To prevent integer overflow. Many programming languages have limits on the size of integers they can represent. When numbers exceed these limits, they wrap around or cause errors. Taking the modulo ensures the numbers remain within a manageable range, which is critical when accumulating large counts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Applying Modulo:&lt;/strong&gt; The modulo operation should be applied whenever you perform an addition or multiplication that might result in a large number. For this problem, it will primarily apply when updating &lt;code&gt;ways[node]&lt;/code&gt; to keep the counts within the required range.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With these prerequisites firmly in mind, you are well-equipped to understand the detailed solution.&lt;/p&gt;
&lt;h2 id="understanding-leetcode-1976-number-of-ways-to-arrive-at-destination"&gt;Understanding Leetcode 1976: Number of Ways to Arrive at Destination&lt;/h2&gt;
&lt;p&gt;The problem "Number of Ways to Arrive at Destination" presents a city with &lt;code&gt;n&lt;/code&gt; intersections, numbered from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;. We are given a 2D integer array &lt;code&gt;roads&lt;/code&gt;, where &lt;code&gt;roads[i] = [ui, vi, timei]&lt;/code&gt; indicates a &lt;code&gt;timei&lt;/code&gt; minute road between intersections &lt;code&gt;ui&lt;/code&gt; and &lt;code&gt;vi&lt;/code&gt;. These roads can be traveled in both directions. Our objective is to find the number of ways to travel from intersection &lt;code&gt;0&lt;/code&gt; (the start) to intersection &lt;code&gt;n-1&lt;/code&gt; (the destination) in the &lt;em&gt;shortest possible time&lt;/em&gt;. Since the number of ways can be huge, we must return it modulo &lt;code&gt;10^9 + 7&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Let's break down the key aspects:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Source and Destination:&lt;/strong&gt; Always fixed at &lt;code&gt;0&lt;/code&gt; and &lt;code&gt;n-1&lt;/code&gt; respectively. This simplifies the problem by having a consistent start and end point.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Non-negative Weights:&lt;/strong&gt; The &lt;code&gt;timei&lt;/code&gt; values are always non-negative, which is a crucial condition for Dijkstra's algorithm to work correctly. If negative weights were allowed, other algorithms like Bellman-Ford or SPFA would be necessary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Undirected Roads:&lt;/strong&gt; Each &lt;code&gt;[ui, vi, timei]&lt;/code&gt; road implies two directed edges: &lt;code&gt;ui -&amp;gt; vi&lt;/code&gt; with &lt;code&gt;timei&lt;/code&gt; and &lt;code&gt;vi -&amp;gt; ui&lt;/code&gt; with &lt;code&gt;timei&lt;/code&gt;. This bidirectionality must be accurately reflected in the graph representation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;"Shortest Possible Time":&lt;/strong&gt; This immediately signals a shortest path algorithm, making Dijkstra a primary candidate. The modification to Dijkstra's will allow us to track more than just the shortest time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;"Number of Ways":&lt;/strong&gt; This is where the standard Dijkstra algorithm falls short. We need to not only find the minimum time but also count &lt;em&gt;how many distinct paths&lt;/em&gt; achieve that minimum time. If multiple paths lead to a node with the same minimum time, all these paths contribute to the total count for that node.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Consider an example:
If there's a path &lt;code&gt;0 -&amp;gt; A -&amp;gt; D&lt;/code&gt; taking 10 minutes and another path &lt;code&gt;0 -&amp;gt; B -&amp;gt; C -&amp;gt; D&lt;/code&gt; also taking 10 minutes, and 10 minutes is the &lt;em&gt;minimum possible time&lt;/em&gt; to reach D, then there are 2 ways to reach D in the shortest time. This problem requires us to aggregate these distinct valid paths.&lt;/p&gt;
&lt;p&gt;This problem is a classic example of extending a standard graph algorithm with dynamic programming principles to gather additional information during the traversal.&lt;/p&gt;
&lt;h2 id="core-idea-and-algorithm-approach"&gt;Core Idea and Algorithm Approach&lt;/h2&gt;
&lt;p&gt;Solving &lt;strong&gt;Leetcode 1976: Number of Ways to Arrive at Destination&lt;/strong&gt; requires a modification of Dijkstra's algorithm. A standard Dijkstra's algorithm only tracks the minimum distance to each node. To count the ways, we need to extend its state.&lt;/p&gt;
&lt;p&gt;The core idea is to maintain two arrays for each node &lt;code&gt;i&lt;/code&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;code&gt;min_time[i]&lt;/code&gt;: The shortest time found so far to reach node &lt;code&gt;i&lt;/code&gt; from the source (node &lt;code&gt;0&lt;/code&gt;). This array behaves exactly like the distance array in standard Dijkstra.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ways[i]&lt;/code&gt;: The number of distinct paths that achieve &lt;code&gt;min_time[i]&lt;/code&gt;. This array is our dynamic programming component, accumulating counts.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We will initialize &lt;code&gt;min_time&lt;/code&gt; for all nodes to infinity (or a very large number) and &lt;code&gt;ways&lt;/code&gt; for all nodes to &lt;code&gt;0&lt;/code&gt;. The source node &lt;code&gt;0&lt;/code&gt; will have &lt;code&gt;min_time[0] = 0&lt;/code&gt; and &lt;code&gt;ways[0] = 1&lt;/code&gt; (there's one way to be at the start at time 0).&lt;/p&gt;
&lt;p&gt;Our modified Dijkstra will work as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;It will still use a min-priority queue to explore nodes. The elements in the priority queue will be &lt;code&gt;(current_time, u)&lt;/code&gt;, representing that we have found a path to node &lt;code&gt;u&lt;/code&gt; taking &lt;code&gt;current_time&lt;/code&gt; minutes. The priority queue ensures we always process the node that is closest to the source first.&lt;/li&gt;
&lt;li&gt;When we extract a node &lt;code&gt;u&lt;/code&gt; with &lt;code&gt;current_time&lt;/code&gt; from the priority queue, we know &lt;code&gt;current_time&lt;/code&gt; is the &lt;em&gt;definite&lt;/em&gt; shortest time to reach &lt;code&gt;u&lt;/code&gt; (just like in standard Dijkstra's). This is because Dijkstra's algorithm processes nodes in increasing order of their shortest path distances.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;For each neighbor &lt;code&gt;v&lt;/code&gt; of &lt;code&gt;u&lt;/code&gt; connected by an edge of weight &lt;code&gt;w&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Calculate the time to reach &lt;code&gt;v&lt;/code&gt; via &lt;code&gt;u&lt;/code&gt;: &lt;code&gt;new_time = current_time + w&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Case 1: &lt;code&gt;new_time &amp;lt; min_time[v]&lt;/code&gt;&lt;/strong&gt;
    This means we've found a &lt;em&gt;strictly shorter&lt;/em&gt; path to &lt;code&gt;v&lt;/code&gt;. We update &lt;code&gt;min_time[v]&lt;/code&gt; to &lt;code&gt;new_time&lt;/code&gt;. Crucially, since this is a new shortest path, the number of ways to reach &lt;code&gt;v&lt;/code&gt; must now be the same as the number of ways to reach &lt;code&gt;u&lt;/code&gt;. So, &lt;code&gt;ways[v] = ways[u]&lt;/code&gt;. Then, we add &lt;code&gt;(new_time, v)&lt;/code&gt; to the priority queue to explore paths originating from &lt;code&gt;v&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Case 2: &lt;code&gt;new_time == min_time[v]&lt;/code&gt;&lt;/strong&gt;
    This is the critical modification. We've found an &lt;em&gt;alternative path&lt;/em&gt; to &lt;code&gt;v&lt;/code&gt; that takes the &lt;em&gt;exact same minimum time&lt;/em&gt; as an existing shortest path. This means we've discovered additional ways to reach &lt;code&gt;v&lt;/code&gt; in the minimum time. Therefore, we &lt;em&gt;add&lt;/em&gt; the number of ways to reach &lt;code&gt;u&lt;/code&gt; (&lt;code&gt;ways[u]&lt;/code&gt;) to &lt;code&gt;ways[v]&lt;/code&gt;. So, &lt;code&gt;ways[v] = (ways[v] + ways[u]) % MOD&lt;/code&gt;. We also add &lt;code&gt;(new_time, v)&lt;/code&gt; to the priority queue, as this path could lead to shortest paths for other nodes, and its contribution to the &lt;code&gt;ways&lt;/code&gt; count needs to be propagated.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Case 3: &lt;code&gt;new_time &amp;gt; min_time[v]&lt;/code&gt;&lt;/strong&gt;
    This path is longer than an already known shortest path to &lt;code&gt;v&lt;/code&gt;. We simply ignore it, as it cannot contribute to the shortest time or the ways to achieve it.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This approach essentially performs a shortest path search while simultaneously accumulating counts for paths that achieve the minimum time. The modular arithmetic is applied whenever we update &lt;code&gt;ways[v]&lt;/code&gt; to prevent overflow.&lt;/p&gt;
&lt;h2 id="detailed-steps-for-solving-leetcode-1976"&gt;Detailed Steps for Solving Leetcode 1976&lt;/h2&gt;
&lt;p&gt;Let's walk through the exact procedure to implement the solution for &lt;strong&gt;Leetcode 1976: Number of Ways to Arrive at Destination&lt;/strong&gt;. We'll use Python for our example implementation.&lt;/p&gt;
&lt;h3 id="step-1-represent-the-graph"&gt;Step 1: Represent the Graph&lt;/h3&gt;
&lt;p&gt;First, we need to efficiently store the city's road network. An adjacency list is ideal for this. Since the roads are undirected, if &lt;code&gt;u&lt;/code&gt; and &lt;code&gt;v&lt;/code&gt; are connected, we add &lt;code&gt;v&lt;/code&gt; to &lt;code&gt;u&lt;/code&gt;'s list and &lt;code&gt;u&lt;/code&gt; to &lt;code&gt;v&lt;/code&gt;'s list with the associated time.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;heapq&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;countPaths&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;roads&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Define modulo constant as specified by the problem&lt;/span&gt;
        &lt;span class="n"&gt;MOD&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;

        &lt;span class="c1"&gt;# 1. Graph Representation: Adjacency List&lt;/span&gt;
        &lt;span class="c1"&gt;# adj[u] will store a list of tuples (v, travel_time) for neighbors of u&lt;/span&gt;
        &lt;span class="n"&gt;adj&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;roads&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="c1"&gt;# Roads are bidirectional (undirected graph)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="step-2-initialize-data-structures"&gt;Step 2: Initialize Data Structures&lt;/h3&gt;
&lt;p&gt;We'll need arrays to store the minimum time and the number of ways to reach each node, along with a priority queue for Dijkstra's algorithm.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;min_time&lt;/code&gt;: Stores the minimum time to reach each intersection from the source. Initialize with infinity for all nodes except the source.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ways&lt;/code&gt;: Stores the number of ways to reach each intersection in &lt;code&gt;min_time&lt;/code&gt;. Initialize with &lt;code&gt;0&lt;/code&gt; for all nodes except the source.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pq&lt;/code&gt;: A min-priority queue to manage nodes to visit, ordered by the current minimum time to reach them.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;        &lt;span class="c1"&gt;# 2. Initialization of Dijkstra&amp;#39;s arrays&lt;/span&gt;
        &lt;span class="c1"&gt;# min_time[i] stores the shortest time found so far to reach node i from node 0&lt;/span&gt;
        &lt;span class="n"&gt;min_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;inf&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;
        &lt;span class="c1"&gt;# ways[i] stores the number of distinct paths that achieve min_time[i]&lt;/span&gt;
        &lt;span class="n"&gt;ways&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;

        &lt;span class="c1"&gt;# Initialize for the source node (node 0)&lt;/span&gt;
        &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;  &lt;span class="c1"&gt;# Time to reach source from source is 0&lt;/span&gt;
        &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;      &lt;span class="c1"&gt;# There&amp;#39;s one way to be at the start at time 0&lt;/span&gt;

        &lt;span class="c1"&gt;# Priority Queue: stores tuples of (current_time, node)&lt;/span&gt;
        &lt;span class="c1"&gt;# It will extract the node with the smallest current_time first&lt;/span&gt;
        &lt;span class="n"&gt;pq&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="c1"&gt;# Start Dijkstra from node 0 with 0 time&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="step-3-implement-modified-dijkstras-algorithm"&gt;Step 3: Implement Modified Dijkstra's Algorithm&lt;/h3&gt;
&lt;p&gt;This is the core of the solution. We'll extract nodes from the priority queue and systematically update &lt;code&gt;min_time&lt;/code&gt; and &lt;code&gt;ways&lt;/code&gt; for their neighbors based on the rules defined in the "Core Idea" section. The loop continues until all reachable nodes have been processed or the priority queue is empty.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;        &lt;span class="c1"&gt;# 3. Modified Dijkstra&amp;#39;s Algorithm&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="c1"&gt;# Extract the node with the smallest time found so far&lt;/span&gt;
            &lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

            &lt;span class="c1"&gt;# Optimization: If we&amp;#39;ve already found a strictly shorter path to &amp;#39;u&amp;#39;&lt;/span&gt;
            &lt;span class="c1"&gt;# than &amp;#39;current_time&amp;#39; (which means this &amp;#39;current_time&amp;#39; entry in PQ is stale),&lt;/span&gt;
            &lt;span class="c1"&gt;# then skip processing this one. This prevents redundant calculations&lt;/span&gt;
            &lt;span class="c1"&gt;# and ensures we always use the true minimum time for &amp;#39;u&amp;#39;.&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="k"&gt;continue&lt;/span&gt;

            &lt;span class="c1"&gt;# Iterate over all neighbors &amp;#39;v&amp;#39; of the current node &amp;#39;u&amp;#39;&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;travel_time&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="c1"&gt;# Calculate the time to reach neighbor &amp;#39;v&amp;#39; through current node &amp;#39;u&amp;#39;&lt;/span&gt;
                &lt;span class="n"&gt;new_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;travel_time&lt;/span&gt;

                &lt;span class="c1"&gt;# Case 1: Found a strictly shorter path to &amp;#39;v&amp;#39;&lt;/span&gt;
                &lt;span class="c1"&gt;# This is the standard Dijkstra&amp;#39;s relaxation step.&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;new_time&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                    &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_time&lt;/span&gt;  &lt;span class="c1"&gt;# Update minimum time&lt;/span&gt;
                    &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;       &lt;span class="c1"&gt;# The number of ways is now solely determined by ways[u]&lt;/span&gt;
                    &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;new_time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="c1"&gt;# Push &amp;#39;v&amp;#39; to PQ to explore further paths&lt;/span&gt;

                &lt;span class="c1"&gt;# Case 2: Found a path with the exact same minimum time to &amp;#39;v&amp;#39;&lt;/span&gt;
                &lt;span class="c1"&gt;# This is the core modification for counting ways.&lt;/span&gt;
                &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;new_time&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                    &lt;span class="c1"&gt;# This means we found an *additional* way to reach &amp;#39;v&amp;#39; in its minimum time.&lt;/span&gt;
                    &lt;span class="c1"&gt;# So, we add the ways from &amp;#39;u&amp;#39; to the existing ways for &amp;#39;v&amp;#39;.&lt;/span&gt;
                    &lt;span class="c1"&gt;# Apply modular arithmetic to prevent integer overflow.&lt;/span&gt;
                    &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="n"&gt;MOD&lt;/span&gt;
                    &lt;span class="c1"&gt;# Crucially, we still push &amp;#39;v&amp;#39; to the PQ. Even though its min_time hasn&amp;#39;t changed,&lt;/span&gt;
                    &lt;span class="c1"&gt;# finding a *new path* to &amp;#39;v&amp;#39; with min_time means that subsequent paths starting&lt;/span&gt;
                    &lt;span class="c1"&gt;# from &amp;#39;v&amp;#39; might now be counted in ways[v], and these paths need to be explored&lt;/span&gt;
                    &lt;span class="c1"&gt;# with the correct way count propagation. The &amp;#39;current_time &amp;gt; min_time[u]&amp;#39; check&lt;/span&gt;
                    &lt;span class="c1"&gt;# at the beginning of the loop efficiently handles potential duplicate entries&lt;/span&gt;
                    &lt;span class="c1"&gt;# from being processed more than necessary after their true min_time is found.&lt;/span&gt;
                    &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;new_time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="step-4-return-the-result"&gt;Step 4: Return the Result&lt;/h3&gt;
&lt;p&gt;Once the priority queue is empty, &lt;code&gt;ways[n-1]&lt;/code&gt; will hold the total number of ways to reach the destination &lt;code&gt;n-1&lt;/code&gt; in the shortest possible time, modulo &lt;code&gt;10^9 + 7&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;        &lt;span class="c1"&gt;# 4. Final Result&lt;/span&gt;
        &lt;span class="c1"&gt;# The answer is the number of ways to reach the destination node (n-1)&lt;/span&gt;
        &lt;span class="c1"&gt;# in the shortest possible time.&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="complete-code-implementation-python"&gt;Complete Code Implementation (Python)&lt;/h3&gt;
&lt;p&gt;Putting it all together, here's the full Python solution for &lt;strong&gt;Leetcode 1976: Number of Ways to Arrive at Destination&lt;/strong&gt;:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;heapq&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;countPaths&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;roads&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Define modulo constant as specified by the problem&lt;/span&gt;
        &lt;span class="n"&gt;MOD&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;

        &lt;span class="c1"&gt;# 1. Graph Representation: Adjacency List&lt;/span&gt;
        &lt;span class="c1"&gt;# adj[u] will store a list of tuples (v, travel_time) for neighbors of u&lt;/span&gt;
        &lt;span class="n"&gt;adj&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;roads&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="c1"&gt;# Roads are bidirectional (undirected graph)&lt;/span&gt;

        &lt;span class="c1"&gt;# 2. Initialization of Dijkstra&amp;#39;s arrays&lt;/span&gt;
        &lt;span class="c1"&gt;# min_time[i] stores the shortest time found so far to reach node i from node 0&lt;/span&gt;
        &lt;span class="n"&gt;min_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;inf&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;
        &lt;span class="c1"&gt;# ways[i] stores the number of distinct paths that achieve min_time[i]&lt;/span&gt;
        &lt;span class="n"&gt;ways&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;

        &lt;span class="c1"&gt;# Initialize for the source node (node 0)&lt;/span&gt;
        &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;  &lt;span class="c1"&gt;# Time to reach source from source is 0&lt;/span&gt;
        &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;      &lt;span class="c1"&gt;# There&amp;#39;s one way to be at the start at time 0&lt;/span&gt;

        &lt;span class="c1"&gt;# Priority Queue: stores tuples of (current_time, node)&lt;/span&gt;
        &lt;span class="c1"&gt;# It will extract the node with the smallest current_time first&lt;/span&gt;
        &lt;span class="n"&gt;pq&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="c1"&gt;# Start Dijkstra from node 0 with 0 time&lt;/span&gt;

        &lt;span class="c1"&gt;# 3. Modified Dijkstra&amp;#39;s Algorithm&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="c1"&gt;# Extract the node with the smallest time found so far&lt;/span&gt;
            &lt;span class="n"&gt;current_time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

            &lt;span class="c1"&gt;# Optimization: If we&amp;#39;ve already found a strictly shorter path to &amp;#39;u&amp;#39; than&lt;/span&gt;
            &lt;span class="c1"&gt;# &amp;#39;current_time&amp;#39; (which means this &amp;#39;current_time&amp;#39; entry in PQ is stale),&lt;/span&gt;
            &lt;span class="c1"&gt;# then skip processing this one. This prevents redundant calculations.&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="k"&gt;continue&lt;/span&gt;

            &lt;span class="c1"&gt;# Iterate over all neighbors &amp;#39;v&amp;#39; of the current node &amp;#39;u&amp;#39;&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;travel_time&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="c1"&gt;# Calculate the time to reach neighbor &amp;#39;v&amp;#39; through current node &amp;#39;u&amp;#39;&lt;/span&gt;
                &lt;span class="n"&gt;new_time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current_time&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;travel_time&lt;/span&gt;

                &lt;span class="c1"&gt;# Case 1: Found a strictly shorter path to &amp;#39;v&amp;#39;&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;new_time&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                    &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_time&lt;/span&gt;  &lt;span class="c1"&gt;# Update minimum time&lt;/span&gt;
                    &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;       &lt;span class="c1"&gt;# The number of ways is now solely determined by ways[u]&lt;/span&gt;
                    &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;new_time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="c1"&gt;# Push &amp;#39;v&amp;#39; to PQ to explore further paths&lt;/span&gt;

                &lt;span class="c1"&gt;# Case 2: Found a path with the exact same minimum time to &amp;#39;v&amp;#39;&lt;/span&gt;
                &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;new_time&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;min_time&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                    &lt;span class="c1"&gt;# This means we found an *additional* way to reach &amp;#39;v&amp;#39; in its minimum time.&lt;/span&gt;
                    &lt;span class="c1"&gt;# So, we add the ways from &amp;#39;u&amp;#39; to the existing ways for &amp;#39;v&amp;#39;.&lt;/span&gt;
                    &lt;span class="c1"&gt;# Apply modular arithmetic to prevent integer overflow.&lt;/span&gt;
                    &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="n"&gt;MOD&lt;/span&gt;
                    &lt;span class="c1"&gt;# Crucially, we still push &amp;#39;v&amp;#39; to the PQ. Even though its min_time hasn&amp;#39;t changed,&lt;/span&gt;
                    &lt;span class="c1"&gt;# finding a *new path* to &amp;#39;v&amp;#39; with min_time means that subsequent paths starting&lt;/span&gt;
                    &lt;span class="c1"&gt;# from &amp;#39;v&amp;#39; might now be counted in ways[v], and these paths need to be explored&lt;/span&gt;
                    &lt;span class="c1"&gt;# with the correct way count propagation. The &amp;#39;current_time &amp;gt; min_time[u]&amp;#39; check&lt;/span&gt;
                    &lt;span class="c1"&gt;# ensures that stale entries don&amp;#39;t cause infinite loops or incorrect behavior.&lt;/span&gt;
                    &lt;span class="n"&gt;heapq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;heappush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;new_time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

        &lt;span class="c1"&gt;# 4. Final Result&lt;/span&gt;
        &lt;span class="c1"&gt;# The answer is the number of ways to reach the destination node (n-1)&lt;/span&gt;
        &lt;span class="c1"&gt;# in the shortest possible time.&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ways&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="example-walkthrough"&gt;Example Walkthrough&lt;/h3&gt;
&lt;p&gt;Let's trace a small example to solidify understanding of how &lt;code&gt;ways&lt;/code&gt; are updated, particularly focusing on the &lt;code&gt;new_time == min_time[v]&lt;/code&gt; case.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;n = 3&lt;/code&gt;, &lt;code&gt;roads = [[0,1,10], [1,2,10], [0,2,20]]&lt;/code&gt;
Source: &lt;code&gt;0&lt;/code&gt;, Destination: &lt;code&gt;2&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Initial State:
&lt;code&gt;min_time = [0, inf, inf]&lt;/code&gt; (inf represents &lt;code&gt;float('inf')&lt;/code&gt;)
&lt;code&gt;ways = [1, 0, 0]&lt;/code&gt;
&lt;code&gt;pq = [(0, 0)]&lt;/code&gt; (time, node)&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pop &lt;code&gt;(0, 0)&lt;/code&gt; from &lt;code&gt;pq&lt;/code&gt;. &lt;code&gt;u = 0&lt;/code&gt;, &lt;code&gt;current_time = 0&lt;/code&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;min_time[0] = 0&lt;/code&gt;, &lt;code&gt;ways[0] = 1&lt;/code&gt;. (&lt;code&gt;current_time&lt;/code&gt; is not greater than &lt;code&gt;min_time[0]&lt;/code&gt;, so not stale).&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Neighbors of &lt;code&gt;0&lt;/code&gt;: &lt;code&gt;(1, 10)&lt;/code&gt;, &lt;code&gt;(2, 20)&lt;/code&gt; (neighbor node, travel time)&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Neighbor &lt;code&gt;v = 1&lt;/code&gt;, &lt;code&gt;travel_time = 10&lt;/code&gt;&lt;/strong&gt;:
    &lt;code&gt;new_time = 0 + 10 = 10&lt;/code&gt;.
    &lt;code&gt;10 &amp;lt; min_time[1]&lt;/code&gt; (&lt;code&gt;inf&lt;/code&gt;):
    &lt;code&gt;min_time[1] = 10&lt;/code&gt;
    &lt;code&gt;ways[1] = ways[0] = 1&lt;/code&gt;
    &lt;code&gt;heapq.heappush(pq, (10, 1))&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Neighbor &lt;code&gt;v = 2&lt;/code&gt;, &lt;code&gt;travel_time = 20&lt;/code&gt;&lt;/strong&gt;:
    &lt;code&gt;new_time = 0 + 20 = 20&lt;/code&gt;.
    &lt;code&gt;20 &amp;lt; min_time[2]&lt;/code&gt; (&lt;code&gt;inf&lt;/code&gt;):
    &lt;code&gt;min_time[2] = 20&lt;/code&gt;
    &lt;code&gt;ways[2] = ways[0] = 1&lt;/code&gt;
    &lt;code&gt;heapq.heappush(pq, (20, 2))&lt;/code&gt;
    &lt;code&gt;pq&lt;/code&gt; is now &lt;code&gt;[(10, 1), (20, 2)]&lt;/code&gt; (order might vary slightly for equal priorities, but for distinct times it's stable).&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pop &lt;code&gt;(10, 1)&lt;/code&gt; from &lt;code&gt;pq&lt;/code&gt;. &lt;code&gt;u = 1&lt;/code&gt;, &lt;code&gt;current_time = 10&lt;/code&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;min_time[1] = 10&lt;/code&gt;, &lt;code&gt;ways[1] = 1&lt;/code&gt;. (&lt;code&gt;current_time == min_time[1]&lt;/code&gt;, not stale).&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Neighbors of &lt;code&gt;1&lt;/code&gt;: &lt;code&gt;(0, 10)&lt;/code&gt;, &lt;code&gt;(2, 10)&lt;/code&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Neighbor &lt;code&gt;v = 0&lt;/code&gt;, &lt;code&gt;travel_time = 10&lt;/code&gt;&lt;/strong&gt;:
    &lt;code&gt;new_time = 10 + 10 = 20&lt;/code&gt;.
    &lt;code&gt;20 &amp;gt; min_time[0]&lt;/code&gt; (&lt;code&gt;0&lt;/code&gt;): Ignore (this path is longer than already known shortest path to 0).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Neighbor &lt;code&gt;v = 2&lt;/code&gt;, &lt;code&gt;travel_time = 10&lt;/code&gt;&lt;/strong&gt;:
    &lt;code&gt;new_time = 10 + 10 = 20&lt;/code&gt;.
    Compare &lt;code&gt;new_time&lt;/code&gt; with &lt;code&gt;min_time[2]&lt;/code&gt; (which is &lt;code&gt;20&lt;/code&gt;):
    &lt;code&gt;new_time == min_time[2]&lt;/code&gt; (both are &lt;code&gt;20&lt;/code&gt;):
    This is an alternative shortest path to &lt;code&gt;v=2&lt;/code&gt;.
    &lt;code&gt;ways[2] = (ways[2] + ways[1]) % MOD = (1 + 1) % MOD = 2&lt;/code&gt;.
    &lt;code&gt;heapq.heappush(pq, (20, 2))&lt;/code&gt;
    &lt;code&gt;pq&lt;/code&gt; is now &lt;code&gt;[(20, 2), (20, 2)]&lt;/code&gt;. (Note: The specific order of two entries with identical priority might vary slightly, but both will be processed).&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pop &lt;code&gt;(20, 2)&lt;/code&gt; from &lt;code&gt;pq&lt;/code&gt;. &lt;code&gt;u = 2&lt;/code&gt;, &lt;code&gt;current_time = 20&lt;/code&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;min_time[2] = 20&lt;/code&gt;, &lt;code&gt;ways[2] = 2&lt;/code&gt;. (&lt;code&gt;current_time == min_time[2]&lt;/code&gt;, not stale).&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Neighbors of &lt;code&gt;2&lt;/code&gt;: &lt;code&gt;(0, 20)&lt;/code&gt;, &lt;code&gt;(1, 10)&lt;/code&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Neighbor &lt;code&gt;v = 0&lt;/code&gt;, &lt;code&gt;travel_time = 20&lt;/code&gt;&lt;/strong&gt;:
    &lt;code&gt;new_time = 20 + 20 = 40&lt;/code&gt;.
    &lt;code&gt;40 &amp;gt; min_time[0]&lt;/code&gt; (&lt;code&gt;0&lt;/code&gt;): Ignore.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Neighbor &lt;code&gt;v = 1&lt;/code&gt;, &lt;code&gt;travel_time = 10&lt;/code&gt;&lt;/strong&gt;:
    &lt;code&gt;new_time = 20 + 10 = 30&lt;/code&gt;.
    &lt;code&gt;30 &amp;gt; min_time[1]&lt;/code&gt; (&lt;code&gt;10&lt;/code&gt;): Ignore.
    &lt;code&gt;pq&lt;/code&gt; is now &lt;code&gt;[(20, 2)]&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pop &lt;code&gt;(20, 2)&lt;/code&gt; from &lt;code&gt;pq&lt;/code&gt;. &lt;code&gt;u = 2&lt;/code&gt;, &lt;code&gt;current_time = 20&lt;/code&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;min_time[2] = 20&lt;/code&gt;, &lt;code&gt;ways[2] = 2&lt;/code&gt;. (&lt;code&gt;current_time == min_time[2]&lt;/code&gt;, not stale).&lt;/li&gt;
&lt;li&gt;Neighbors of &lt;code&gt;2&lt;/code&gt;: (Same as above, will be ignored as they lead to longer paths).
&lt;code&gt;pq&lt;/code&gt; is now empty.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Algorithm terminates.&lt;/p&gt;
&lt;p&gt;Final State:
&lt;code&gt;min_time = [0, 10, 20]&lt;/code&gt;
&lt;code&gt;ways = [1, 1, 2]&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Result: &lt;code&gt;ways[n-1]&lt;/code&gt; (i.e., &lt;code&gt;ways[2]&lt;/code&gt;) is &lt;code&gt;2&lt;/code&gt;. This correctly identifies two paths that achieve the minimum time of 20 minutes to reach node 2:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;code&gt;0 -&amp;gt; 2&lt;/code&gt; (direct path, time 20)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;0 -&amp;gt; 1 -&amp;gt; 2&lt;/code&gt; (via node 1, time 10 + 10 = 20)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This example clearly illustrates how the &lt;code&gt;ways&lt;/code&gt; count is accumulated when multiple paths yield the same minimum time.&lt;/p&gt;
&lt;h2 id="complexity-analysis"&gt;Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the performance characteristics of our solution is vital for competitive programming and software engineering.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;The time complexity of this modified Dijkstra's algorithm is largely similar to the standard version.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Graph Construction:&lt;/strong&gt; Building the adjacency list takes &lt;code&gt;O(V + E)&lt;/code&gt; time, where &lt;code&gt;V&lt;/code&gt; is the number of vertices (intersections) and &lt;code&gt;E&lt;/code&gt; is the number of edges (roads). Each road contributes two entries to the adjacency list due to the undirected nature.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dijkstra's Algorithm Loop:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;In the worst case, each vertex &lt;code&gt;V&lt;/code&gt; is extracted from the priority queue once for its &lt;em&gt;final&lt;/em&gt; shortest time. However, due to the &lt;code&gt;new_time == min_time[v]&lt;/code&gt; condition, a node can be pushed into the priority queue multiple times if new, equally optimal paths are discovered.&lt;/li&gt;
&lt;li&gt;Each &lt;code&gt;heapq.heappush&lt;/code&gt; and &lt;code&gt;heapq.heappop&lt;/code&gt; operation takes &lt;code&gt;O(log K)&lt;/code&gt; time, where &lt;code&gt;K&lt;/code&gt; is the number of elements in the priority queue. In the worst case, &lt;code&gt;K&lt;/code&gt; can be up to &lt;code&gt;E&lt;/code&gt; (or &lt;code&gt;V&lt;/code&gt; for sparse graphs if each node is added at most once).&lt;/li&gt;
&lt;li&gt;For a graph with &lt;code&gt;V&lt;/code&gt; vertices and &lt;code&gt;E&lt;/code&gt; edges using a binary heap (like Python's &lt;code&gt;heapq&lt;/code&gt;), the complexity is typically &lt;code&gt;O(E log V)&lt;/code&gt; if each node is pushed at most once. However, because a node &lt;code&gt;v&lt;/code&gt; can be pushed into the priority queue multiple times when &lt;code&gt;new_time == min_time[v]&lt;/code&gt;, the tightest upper bound becomes &lt;code&gt;O(E log E)&lt;/code&gt; in the absolute worst case (if every edge relaxation leads to an update and a push). Since &lt;code&gt;E&lt;/code&gt; can be at most &lt;code&gt;V^2&lt;/code&gt;, &lt;code&gt;log E&lt;/code&gt; is &lt;code&gt;2 log V&lt;/code&gt;, so it's often still simplified to &lt;code&gt;O(E log V)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Therefore, the overall time complexity is &lt;strong&gt;&lt;code&gt;O(E log V)&lt;/code&gt;&lt;/strong&gt; or, more accurately, &lt;strong&gt;&lt;code&gt;O(E log E)&lt;/code&gt;&lt;/strong&gt; with a binary heap. Given the constraints in typical Leetcode problems (&lt;code&gt;V&lt;/code&gt; up to &lt;code&gt;200&lt;/code&gt;, &lt;code&gt;E&lt;/code&gt; up to &lt;code&gt;V * (V-1) / 2&lt;/code&gt;), this is efficient enough.&lt;/p&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;The space complexity is determined by the data structures used.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Adjacency List:&lt;/strong&gt; Stores &lt;code&gt;O(V + E)&lt;/code&gt; elements, as each vertex is stored once, and each edge is stored twice (for both directions).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;min_time&lt;/code&gt; Array:&lt;/strong&gt; Requires &lt;code&gt;O(V)&lt;/code&gt; space to store minimum times for each vertex.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;ways&lt;/code&gt; Array:&lt;/strong&gt; Requires &lt;code&gt;O(V)&lt;/code&gt; space to store the number of ways for each vertex.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Priority Queue:&lt;/strong&gt; In the worst case, can hold up to &lt;code&gt;O(E)&lt;/code&gt; elements (if many nodes are pushed multiple times before being definitively settled).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Thus, the overall space complexity is &lt;strong&gt;&lt;code&gt;O(V + E)&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;h2 id="common-mistakes-and-troubleshooting"&gt;Common Mistakes and Troubleshooting&lt;/h2&gt;
&lt;p&gt;Even with a solid understanding, specific pitfalls can lead to incorrect or inefficient solutions for &lt;strong&gt;Leetcode 1976: Number of Ways to Arrive at Destination&lt;/strong&gt;. Being aware of these common mistakes can help you debug and refine your approach.&lt;/p&gt;
&lt;h3 id="1-incorrectly-handling-new_time-min_timev"&gt;1. Incorrectly Handling &lt;code&gt;new_time == min_time[v]&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;This is arguably the most critical and frequently missed detail, directly affecting the core logic of counting ways.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; If &lt;code&gt;new_time == min_time[v]&lt;/code&gt;, simply assigning &lt;code&gt;ways[v] = ways[u]&lt;/code&gt; instead of &lt;code&gt;ways[v] = (ways[v] + ways[u]) % MOD&lt;/code&gt;. This overwrites any previously found ways to reach &lt;code&gt;v&lt;/code&gt; in the same minimum time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Why it's wrong:&lt;/strong&gt; This overwrites previous ways instead of accumulating them. The problem specifically asks for the "number of ways," implying all paths that achieve the minimum time must be counted. If &lt;code&gt;ways[v]&lt;/code&gt; is simply assigned &lt;code&gt;ways[u]&lt;/code&gt;, you would only count the ways from the &lt;em&gt;last&lt;/em&gt; path that found an equal minimum time, losing all other valid paths.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Correction:&lt;/strong&gt; Always use &lt;code&gt;ways[v] = (ways[v] + ways[u]) % MOD&lt;/code&gt; when &lt;code&gt;new_time == min_time[v]&lt;/code&gt; to sum up all contributing paths.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-forgetting-modular-arithmetic"&gt;2. Forgetting Modular Arithmetic&lt;/h3&gt;
&lt;p&gt;The problem statement explicitly mentions that the number of ways can be very large and requires the result modulo &lt;code&gt;10^9 + 7&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Not applying &lt;code&gt;% MOD&lt;/code&gt; when updating &lt;code&gt;ways[v]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Why it's wrong:&lt;/strong&gt; This will lead to integer overflow for large test cases. Most programming languages have a maximum integer value (e.g., &lt;code&gt;2^31 - 1&lt;/code&gt; or &lt;code&gt;2^63 - 1&lt;/code&gt;), and exceeding this limit can result in incorrect negative numbers, wrapped-around values, or runtime errors.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Correction:&lt;/strong&gt; Ensure &lt;code&gt;ways[v] = (ways[v] + ways[u]) % MOD&lt;/code&gt; is used whenever &lt;code&gt;ways[v]&lt;/code&gt; is incremented (or initialized based on another &lt;code&gt;ways&lt;/code&gt; value). Define &lt;code&gt;MOD = 10**9 + 7&lt;/code&gt; at the beginning of your solution.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-incorrect-graph-representation"&gt;3. Incorrect Graph Representation&lt;/h3&gt;
&lt;p&gt;Misinterpreting the undirected nature of the roads is a common oversight in graph problems.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Only adding &lt;code&gt;adj[u].append((v, time))&lt;/code&gt; for each road &lt;code&gt;[u, v, time]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Why it's wrong:&lt;/strong&gt; This creates a directed graph where you can travel from &lt;code&gt;u&lt;/code&gt; to &lt;code&gt;v&lt;/code&gt; but not necessarily from &lt;code&gt;v&lt;/code&gt; to &lt;code&gt;u&lt;/code&gt;. The problem explicitly states roads can be traveled in "both directions," meaning an undirected graph is required. Failing to represent this means the algorithm might miss valid shortest paths that use a reverse traversal.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Correction:&lt;/strong&gt; For every &lt;code&gt;[u, v, time]&lt;/code&gt; in &lt;code&gt;roads&lt;/code&gt;, add both &lt;code&gt;adj[u].append((v, time))&lt;/code&gt; and &lt;code&gt;adj[v].append((u, time))&lt;/code&gt; to correctly model the bidirectionality.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-initialization-errors"&gt;4. Initialization Errors&lt;/h3&gt;
&lt;p&gt;Properly setting up &lt;code&gt;min_time&lt;/code&gt; and &lt;code&gt;ways&lt;/code&gt; for the source node and all other nodes is fundamental to Dijkstra's.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Not setting &lt;code&gt;min_time[0] = 0&lt;/code&gt;. If &lt;code&gt;min_time[0]&lt;/code&gt; starts as &lt;code&gt;infinity&lt;/code&gt;, the algorithm won't correctly start its traversal from node 0.&lt;/li&gt;
&lt;li&gt;Not setting &lt;code&gt;ways[0] = 1&lt;/code&gt;. If &lt;code&gt;ways[0]&lt;/code&gt; is &lt;code&gt;0&lt;/code&gt;, all subsequent &lt;code&gt;ways&lt;/code&gt; counts will also incorrectly be &lt;code&gt;0&lt;/code&gt;, as nothing propagates from the source.&lt;/li&gt;
&lt;li&gt;Forgetting to initialize &lt;code&gt;min_time&lt;/code&gt; for other nodes to &lt;code&gt;infinity&lt;/code&gt; (or a very large number) and &lt;code&gt;ways&lt;/code&gt; for other nodes to &lt;code&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Why it's wrong:&lt;/strong&gt; An incorrect initial state will propagate errors throughout Dijkstra's algorithm. The base cases for the shortest path and the number of ways must be correctly established for the source node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Correction:&lt;/strong&gt; Initialize &lt;code&gt;min_time = [float('inf')] * n&lt;/code&gt;, then specifically set &lt;code&gt;min_time[0] = 0&lt;/code&gt;. Initialize &lt;code&gt;ways = [0] * n&lt;/code&gt;, then set &lt;code&gt;ways[0] = 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-stale-entries-in-priority-queue-less-common-with-proper-checks"&gt;5. Stale Entries in Priority Queue (Less common with proper checks)&lt;/h3&gt;
&lt;p&gt;While the &lt;code&gt;if current_time &amp;gt; min_time[u]: continue&lt;/code&gt; check handles this gracefully, understanding its purpose is important.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Not including the check &lt;code&gt;if current_time &amp;gt; min_time[u]: continue&lt;/code&gt; at the top of the &lt;code&gt;while&lt;/code&gt; loop.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Why it's wrong (without the check):&lt;/strong&gt; If a node &lt;code&gt;u&lt;/code&gt; is added to the priority queue multiple times with different times (e.g., first with time 10, then later with time 5 via a shorter path), the PQ might still contain the &lt;code&gt;(10, u)&lt;/code&gt; entry even after &lt;code&gt;min_time[u]&lt;/code&gt; has been updated to &lt;code&gt;5&lt;/code&gt;. If this stale &lt;code&gt;(10, u)&lt;/code&gt; entry is popped and processed, you might process &lt;code&gt;u&lt;/code&gt; with a suboptimal time, potentially propagating longer paths or doing redundant work.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Correction:&lt;/strong&gt; Always include the &lt;code&gt;if current_time &amp;gt; min_time[u]: continue&lt;/code&gt; check at the beginning of the &lt;code&gt;while&lt;/code&gt; loop to ensure you only process the most optimal path found so far for any given node. This ensures correctness and efficiency by preventing unnecessary re-processing of already optimized paths.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;By carefully considering these common mistakes and adhering to the detailed steps, you can confidently implement a correct and efficient solution for &lt;strong&gt;Leetcode 1976: Number of Ways to Arrive at Destination&lt;/strong&gt;.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: Why can't a standard Dijkstra's algorithm solve Leetcode 1976 directly?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A standard Dijkstra's algorithm is designed to find only one shortest path (or the shortest distance) from a source to all other nodes. It doesn't inherently track or count multiple distinct paths that might achieve the exact same minimum distance. Leetcode 1976 requires counting all such paths, which necessitates additional logic beyond basic shortest path discovery.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Why is modular arithmetic necessary in this problem?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The problem statement specifies that the "number of ways" can be very large. Without modular arithmetic (e.g., modulo &lt;code&gt;10^9 + 7&lt;/code&gt;), the count of paths could exceed the maximum value representable by standard integer data types, leading to integer overflow and incorrect results. Applying the modulo operation at each addition keeps the numbers within a manageable range.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the time complexity of this modified Dijkstra's solution, and what contributes to it?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The time complexity is typically &lt;code&gt;O(E log V)&lt;/code&gt; or &lt;code&gt;O(E log E)&lt;/code&gt; when using a binary heap. This comes from building the adjacency list (&lt;code&gt;O(V+E)&lt;/code&gt;) and the Dijkstra's traversal itself. Each edge &lt;code&gt;E&lt;/code&gt; can potentially lead to a relaxation (distance update) and a push operation on the priority queue, which takes &lt;code&gt;O(log K)&lt;/code&gt; time, where &lt;code&gt;K&lt;/code&gt; is the size of the priority queue, bounded by &lt;code&gt;E&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Dijkstra's Algorithm on Wikipedia:&lt;/strong&gt; &lt;a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm"&gt;https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;LeetCode 1976 Problem Page:&lt;/strong&gt; &lt;a href="https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/"&gt;https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dijkstra's Shortest Path Algorithm - GeeksforGeeks:&lt;/strong&gt; &lt;a href="https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/"&gt;https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graph Theory on Wikipedia:&lt;/strong&gt; &lt;a href="https://en.wikipedia.org/wiki/Graph_theory"&gt;https://en.wikipedia.org/wiki/Graph_theory&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dynamic Programming on Wikipedia:&lt;/strong&gt; &lt;a href="https://en.wikipedia.org/wiki/Dynamic_programming"&gt;https://en.wikipedia.org/wiki/Dynamic_programming&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="LeetCode"/><category term="Dynamic Programming"/><category term="Coding Interview"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/leetcode-1976-number-of-ways-arrive-destination-tutorial.webp" width="1200"/><media:title type="plain">Leetcode 1976: Number of Ways to Arrive at Destination Explained</media:title><media:description type="plain">Master Leetcode 1976: Number of Ways to Arrive at Destination. This guide explains the modified Dijkstra's algorithm to solve this complex graph problem.</media:description></entry><entry><title>Topological Sort using DFS &amp; BFS in Python, C++, Java</title><link href="https://analyticsdrive.tech/topological-sort-dfs-bfs-python-cpp-java/" rel="alternate"/><published>2026-02-24T13:59:00+05:30</published><updated>2026-04-21T04:43:51.769467+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-24:/topological-sort-dfs-bfs-python-cpp-java/</id><summary type="html">&lt;p&gt;Learn to implement topological sort using DFS and BFS algorithms across Python, C++, and Java. Master this critical graph algorithm for DAGs.&lt;/p&gt;</summary><content type="html">&lt;p&gt;Directed Acyclic Graphs (DAGs) are fundamental in computer science, modeling everything from task dependencies to course prerequisites. At the heart of effectively managing these structures lies the &lt;strong&gt;Topological Sort&lt;/strong&gt;, an algorithm that linearizes the vertices of a DAG such that for every directed edge from vertex &lt;code&gt;u&lt;/code&gt; to vertex &lt;code&gt;v&lt;/code&gt;, &lt;code&gt;u&lt;/code&gt; comes before &lt;code&gt;v&lt;/code&gt; in the ordering. This comprehensive guide will walk you through implementing &lt;strong&gt;Topological Sort using DFS &amp;amp; BFS in Python, C++, Java&lt;/strong&gt;, equipping you with the skills to tackle complex dependency problems. We'll explore both Depth-First Search (DFS) and Breadth-First Search (BFS) based approaches, providing detailed explanations and ready-to-use code examples in each language.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-mastering-topological-sort"&gt;Prerequisites for Mastering Topological Sort&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#basic-graph-theory-knowledge"&gt;Basic Graph Theory Knowledge&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-depth-first-search-dfs"&gt;Understanding Depth-First Search (DFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-breadth-first-search-bfs"&gt;Understanding Breadth-First Search (BFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#familiarity-with-python-c-and-java"&gt;Familiarity with Python, C++, and Java&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#what-is-topological-sort"&gt;What is Topological Sort?&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#key-characteristics-of-topological-sort"&gt;Key Characteristics of Topological Sort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#real-world-applications-of-topological-sort"&gt;Real-world Applications of Topological Sort&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-topological-sort-using-dfs-in-python-c-and-java"&gt;Implementing Topological Sort using DFS in Python, C++, and Java&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#understanding-the-dfs-algorithm-for-topological-sort"&gt;Understanding the DFS Algorithm for Topological Sort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#steps-for-dfs-based-topological-sort"&gt;Steps for DFS-based Topological Sort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#1-initialize-data-structures"&gt;1. Initialize Data Structures&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-implement-the-dfs-helper-function"&gt;2. Implement the DFS Helper Function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-mark-node-as-visiting"&gt;3. Mark Node as Visiting&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-traverse-neighbors"&gt;4. Traverse Neighbors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-mark-node-as-visited-and-add-to-result"&gt;5. Mark Node as Visited and Add to Result&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6-iterate-through-all-nodes"&gt;6. Iterate Through All Nodes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-implementation-dfs"&gt;Python Implementation (DFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#explanation-of-python-dfs-code"&gt;Explanation of Python DFS Code&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#c-implementation-dfs"&gt;C++ Implementation (DFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#explanation-of-c-dfs-code"&gt;Explanation of C++ DFS Code&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#java-implementation-dfs"&gt;Java Implementation (DFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#explanation-of-java-dfs-code"&gt;Explanation of Java DFS Code&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-topological-sort-using-bfs-kahns-algorithm-in-python-c-and-java"&gt;Implementing Topological Sort using BFS (Kahn's Algorithm) in Python, C++, and Java&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#understanding-kahns-algorithm"&gt;Understanding Kahn's Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#steps-for-bfs-based-topological-sort-kahns-algorithm"&gt;Steps for BFS-based Topological Sort (Kahn's Algorithm)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#1-compute-in-degrees"&gt;1. Compute In-degrees&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-initialize-queue-with-zero-in-degree-nodes"&gt;2. Initialize Queue with Zero In-degree Nodes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-process-queue"&gt;3. Process Queue&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-check-for-cycles"&gt;4. Check for Cycles&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-implementation-bfs-kahns-algorithm"&gt;Python Implementation (BFS - Kahn's Algorithm)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#explanation-of-python-bfs-code"&gt;Explanation of Python BFS Code&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#c-implementation-bfs-kahns-algorithm"&gt;C++ Implementation (BFS - Kahn's Algorithm)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#explanation-of-c-bfs-code"&gt;Explanation of C++ BFS Code&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#java-implementation-bfs-kahns-algorithm"&gt;Java Implementation (BFS - Kahn's Algorithm)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#explanation-of-java-bfs-code"&gt;Explanation of Java BFS Code&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#comparing-dfs-and-bfs-approaches-for-topological-sort"&gt;Comparing DFS and BFS Approaches for Topological Sort&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#similarities"&gt;Similarities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#differences"&gt;Differences&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#when-to-use-which"&gt;When to Use Which?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity-ov-e"&gt;Time Complexity: O(V + E)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity-ov-e"&gt;Space Complexity: O(V + E)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-how-to-avoid-them"&gt;Common Mistakes and How to Avoid Them&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-forgetting-cycle-detection"&gt;1. Forgetting Cycle Detection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-incorrect-in-degree-calculation-bfs"&gt;2. Incorrect In-degree Calculation (BFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-not-handling-disconnected-components"&gt;3. Not Handling Disconnected Components&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-graph-representation-errors"&gt;4. Graph Representation Errors&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-off-by-one-errors-in-indexing"&gt;5. Off-by-One Errors in Indexing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6-incorrect-dfs-post-order-processing"&gt;6. Incorrect DFS Post-order Processing&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id="prerequisites-for-mastering-topological-sort"&gt;Prerequisites for Mastering Topological Sort&lt;/h2&gt;
&lt;p&gt;Before diving into the intricacies of topological sort, a solid foundation in certain computer science concepts is highly recommended. These prerequisites will ensure you can fully grasp the algorithms and their implementations without getting bogged down by basic concepts.&lt;/p&gt;
&lt;h3 id="basic-graph-theory-knowledge"&gt;Basic Graph Theory Knowledge&lt;/h3&gt;
&lt;p&gt;A fundamental understanding of &lt;a href="/cses-labyrinth-problem-python-java-cpp-guide/"&gt;graph theory&lt;/a&gt; is essential. This includes knowing what a graph is, the difference between directed and undirected graphs, and what edges and vertices represent. Familiarity with graph representations, specifically adjacency lists, will be particularly helpful as most implementations rely on this structure.&lt;/p&gt;
&lt;h3 id="understanding-depth-first-search-dfs"&gt;Understanding Depth-First Search (DFS)&lt;/h3&gt;
&lt;p&gt;DFS is a graph traversal algorithm that explores as far as possible along each branch before backtracking. It's often implemented recursively or using an explicit stack. A good grasp of how &lt;a href="/leetcode-417-pacific-atlantic-water-flow-dfs-solution/"&gt;DFS works&lt;/a&gt;, its recursive nature, and its applications (like cycle detection) will be crucial for understanding the DFS-based topological sort.&lt;/p&gt;
&lt;h3 id="understanding-breadth-first-search-bfs"&gt;Understanding Breadth-First Search (BFS)&lt;/h3&gt;
&lt;p&gt;BFS is another graph traversal algorithm that explores all the neighbor nodes at the present depth before moving on to the nodes at the next depth level. It's typically implemented using a queue. Understanding how &lt;a href="/leetcode-127-word-ladder-bfs-tutorial/"&gt;BFS explores a graph&lt;/a&gt; layer by layer and its uses (like finding the shortest path in unweighted graphs) is vital for the BFS-based topological sort.&lt;/p&gt;
&lt;h3 id="familiarity-with-python-c-and-java"&gt;Familiarity with Python, C++, and Java&lt;/h3&gt;
&lt;p&gt;This tutorial provides code examples in Python, C++, and Java. While you don't need to be an expert in all three, a basic understanding of programming concepts in at least one of these languages (data structures, functions/methods, loops, conditional statements) is necessary to follow the code and adapt it to your needs. Concepts like lists/vectors, dictionaries/maps, and queues will be heavily utilized.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="what-is-topological-sort"&gt;What is Topological Sort?&lt;/h2&gt;
&lt;p&gt;Topological sort is a linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge &lt;code&gt;(u, v)&lt;/code&gt;, vertex &lt;code&gt;u&lt;/code&gt; comes before vertex &lt;code&gt;v&lt;/code&gt; in the ordering. It's important to reiterate that a topological sort is only possible for DAGs; graphs containing cycles cannot be topologically sorted.&lt;/p&gt;
&lt;h3 id="key-characteristics-of-topological-sort"&gt;Key Characteristics of Topological Sort&lt;/h3&gt;
&lt;p&gt;A topological sort holds several important characteristics that define its utility and behavior:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Applicable Only to DAGs:&lt;/strong&gt; The most crucial characteristic is that topological sort can only be performed on a Directed Acyclic Graph. If a graph contains a cycle, no linear ordering can satisfy the condition that &lt;code&gt;u&lt;/code&gt; comes before &lt;code&gt;v&lt;/code&gt; for every edge &lt;code&gt;(u, v)&lt;/code&gt; within the cycle. Detecting cycles is often an implicit part of topological sort algorithms.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not Necessarily Unique:&lt;/strong&gt; For a given DAG, there might be multiple valid topological sorts. If a graph has two vertices &lt;code&gt;u&lt;/code&gt; and &lt;code&gt;v&lt;/code&gt; with no directed path between them, their relative order in a topological sort can vary. For example, in a graph with edges &lt;code&gt;(A, B)&lt;/code&gt; and &lt;code&gt;(A, C)&lt;/code&gt; but no edge between &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt;, both &lt;code&gt;A, B, C&lt;/code&gt; and &lt;code&gt;A, C, B&lt;/code&gt; could be valid sorts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dependency Resolution:&lt;/strong&gt; The primary utility of topological sort lies in resolving dependencies. Tasks that must be completed before others are naturally ordered. This makes it invaluable in scheduling, build systems, and course sequencing.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="real-world-applications-of-topological-sort"&gt;Real-world Applications of Topological Sort&lt;/h3&gt;
&lt;p&gt;The practical applications of topological sort are extensive, making it a highly relevant algorithm for various computational problems.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Task Scheduling:&lt;/strong&gt; In project management, some tasks must be completed before others can begin. A topological sort can determine a valid sequence for completing all tasks. For instance, compiling code, linking libraries, and then running tests form a dependency chain where a topological sort dictates the build order.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Course Scheduling/Prerequisites:&lt;/strong&gt; University courses often have prerequisites. To graduate, a student must take courses in an order that satisfies all prerequisites. A topological sort can help determine a valid sequence of courses.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dependency Resolution in Software Builds:&lt;/strong&gt; Compilers and build systems (like &lt;code&gt;make&lt;/code&gt; or Maven) use topological sort to determine the order in which files or modules need to be compiled or built, ensuring that &lt;a href="/leetcode-269-alien-dictionary-code-python-java-cpp/"&gt;dependencies are satisfied first&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Serialization:&lt;/strong&gt; In some serialization formats or database systems, objects might depend on other objects. A topological sort can provide an order for saving or loading objects to maintain referential integrity.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pipeline Processing:&lt;/strong&gt; In data processing pipelines or workflow management, different stages might depend on the output of previous stages. Topological sort helps in orchestrating these stages in the correct sequence.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id="implementing-topological-sort-using-dfs-in-python-c-and-java"&gt;Implementing Topological Sort using DFS in Python, C++, and Java&lt;/h2&gt;
&lt;p&gt;The DFS-based approach to topological sort relies on the property that in a DAG, if we perform a DFS traversal, a vertex &lt;code&gt;u&lt;/code&gt; will only finish its traversal after all vertices reachable from &lt;code&gt;u&lt;/code&gt; have finished their traversal. This implies that if we add vertices to a list or stack &lt;em&gt;after&lt;/em&gt; all their descendants have been visited, we will get a reverse topological order. Reversing this list or popping from the stack yields a valid topological sort.&lt;/p&gt;
&lt;h3 id="understanding-the-dfs-algorithm-for-topological-sort"&gt;Understanding the DFS Algorithm for Topological Sort&lt;/h3&gt;
&lt;p&gt;The core idea is to use a recursive DFS traversal. When a node's exploration is complete (meaning all its neighbors and their descendants have been visited), that node is added to the topological order. This ensures that any node &lt;code&gt;u&lt;/code&gt; is added to the order only after all nodes &lt;code&gt;v&lt;/code&gt; for which there's a path &lt;code&gt;u -&amp;gt; ... -&amp;gt; v&lt;/code&gt; have been processed.&lt;/p&gt;
&lt;p&gt;We typically use three states for nodes during DFS:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Unvisited:&lt;/strong&gt; The node has not been visited yet.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visiting (Grey):&lt;/strong&gt; The node is currently in the recursion stack, being explored. This state is crucial for cycle detection. If we encounter a 'visiting' node again, it means a cycle exists.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visited (Black):&lt;/strong&gt; The node and all its descendants have been fully explored.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="steps-for-dfs-based-topological-sort"&gt;Steps for DFS-based Topological Sort&lt;/h3&gt;
&lt;p&gt;Here’s a step-by-step breakdown of how to implement topological sort using DFS:&lt;/p&gt;
&lt;h3 id="1-initialize-data-structures"&gt;1. Initialize Data Structures&lt;/h3&gt;
&lt;p&gt;You'll need an adjacency list to represent the graph, a &lt;code&gt;visited&lt;/code&gt; set/array to track node states (unvisited, visiting, visited), and a list or stack to store the topological order.&lt;/p&gt;
&lt;h3 id="2-implement-the-dfs-helper-function"&gt;2. Implement the DFS Helper Function&lt;/h3&gt;
&lt;p&gt;Create a recursive &lt;code&gt;dfs&lt;/code&gt; function that takes a node, the adjacency list, the &lt;code&gt;visited&lt;/code&gt; tracker, and the result list/stack as arguments.&lt;/p&gt;
&lt;h3 id="3-mark-node-as-visiting"&gt;3. Mark Node as Visiting&lt;/h3&gt;
&lt;p&gt;When &lt;code&gt;dfs&lt;/code&gt; is called for a node &lt;code&gt;u&lt;/code&gt;, mark &lt;code&gt;u&lt;/code&gt; as &lt;code&gt;visiting&lt;/code&gt; (e.g., &lt;code&gt;grey&lt;/code&gt;). This state is vital for detecting cycles.&lt;/p&gt;
&lt;h3 id="4-traverse-neighbors"&gt;4. Traverse Neighbors&lt;/h3&gt;
&lt;p&gt;Iterate through all neighbors &lt;code&gt;v&lt;/code&gt; of &lt;code&gt;u&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;*   If `v` is `unvisited`, recursively call `dfs(v)`.
*   If `v` is `visiting`, a cycle is detected. Since topological sort is only for DAGs, you can throw an error or handle it as per requirements.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="5-mark-node-as-visited-and-add-to-result"&gt;5. Mark Node as Visited and Add to Result&lt;/h3&gt;
&lt;p&gt;After visiting all neighbors of &lt;code&gt;u&lt;/code&gt; and their subgraphs, mark &lt;code&gt;u&lt;/code&gt; as &lt;code&gt;visited&lt;/code&gt; (e.g., &lt;code&gt;black&lt;/code&gt;). Then, add &lt;code&gt;u&lt;/code&gt; to the &lt;em&gt;front&lt;/em&gt; of your result list or &lt;em&gt;push&lt;/em&gt; it onto a stack. This ensures the correct order.&lt;/p&gt;
&lt;h3 id="6-iterate-through-all-nodes"&gt;6. Iterate Through All Nodes&lt;/h3&gt;
&lt;p&gt;In your main function, loop through all nodes in the graph. If a node is &lt;code&gt;unvisited&lt;/code&gt;, start a DFS traversal from that node. This handles disconnected components of the graph.&lt;/p&gt;
&lt;h3 id="python-implementation-dfs"&gt;Python Implementation (DFS)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;collections&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;defaultdict&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# 0: unvisited, 1: visiting (grey), 2: visited (black)&lt;/span&gt;
        &lt;span class="n"&gt;visited_state&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;numVertices&lt;/span&gt;
        &lt;span class="n"&gt;result_stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt; &lt;span class="c1"&gt;# Using a list as a stack and then reversing&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;visited_state&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;visited_state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result_stack&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt; &lt;span class="c1"&gt;# Cycle detected, topological sort not possible&lt;/span&gt;

        &lt;span class="c1"&gt;# The result_stack has elements in reverse topological order, so reverse it&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result_stack&lt;/span&gt;&lt;span class="p"&gt;[::&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;visited_state&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result_stack&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;visited_state&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Mark as visiting&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;visited_state&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# Unvisited&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;visited_state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result_stack&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt; &lt;span class="c1"&gt;# Propagate cycle detection&lt;/span&gt;
            &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;visited_state&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# Visiting, implies a cycle&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;

        &lt;span class="n"&gt;visited_state&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="c1"&gt;# Mark as visited&lt;/span&gt;
        &lt;span class="n"&gt;result_stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Add to stack after all descendants are visited&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;

&lt;span class="c1"&gt;# Example Usage&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="vm"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;__main__&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;solver&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

    &lt;span class="c1"&gt;# Example 1: Simple DAG&lt;/span&gt;
    &lt;span class="c1"&gt;# 0 -&amp;gt; 1&lt;/span&gt;
    &lt;span class="c1"&gt;# 0 -&amp;gt; 2&lt;/span&gt;
    &lt;span class="c1"&gt;# 1 -&amp;gt; 3&lt;/span&gt;
    &lt;span class="c1"&gt;# 2 -&amp;gt; 3&lt;/span&gt;
    &lt;span class="c1"&gt;# numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]&lt;/span&gt;
    &lt;span class="c1"&gt;# adj: {0: [1, 2], 1: [3], 2: [3], 3: []}&lt;/span&gt;
    &lt;span class="n"&gt;numVertices1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;defaultdict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Python DFS Topological Sort 1: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Expected: e.g., [0, 2, 1, 3] or [0, 1, 2, 3]&lt;/span&gt;

    &lt;span class="c1"&gt;# Example 2: More complex DAG&lt;/span&gt;
    &lt;span class="c1"&gt;# 5 -&amp;gt; 0, 5 -&amp;gt; 2&lt;/span&gt;
    &lt;span class="c1"&gt;# 4 -&amp;gt; 0, 4 -&amp;gt; 1&lt;/span&gt;
    &lt;span class="c1"&gt;# 2 -&amp;gt; 3&lt;/span&gt;
    &lt;span class="c1"&gt;# 3 -&amp;gt; 1&lt;/span&gt;
    &lt;span class="n"&gt;numVertices2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;defaultdict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Python DFS Topological Sort 2: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Expected: e.g., [4, 5, 2, 3, 1, 0]&lt;/span&gt;

    &lt;span class="c1"&gt;# Example 3: Graph with a cycle (0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0)&lt;/span&gt;
    &lt;span class="n"&gt;numVertices3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;
    &lt;span class="n"&gt;adj3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;defaultdict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Python DFS Topological Sort with cycle: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Expected: []&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="explanation-of-python-dfs-code"&gt;Explanation of Python DFS Code&lt;/h3&gt;
&lt;p&gt;The Python implementation uses a &lt;code&gt;visited_state&lt;/code&gt; list to track the three states (0: unvisited, 1: visiting, 2: visited). The &lt;code&gt;_dfs&lt;/code&gt; helper function recursively traverses the graph. When a node is fully explored (all its children and their descendants), it's appended to &lt;code&gt;result_stack&lt;/code&gt;. This stack will hold nodes in reverse topological order. Finally, &lt;code&gt;result_stack[::-1]&lt;/code&gt; reverses it to give the correct topological sort. Cycle detection is handled by checking &lt;code&gt;visited_state[v] == 1&lt;/code&gt;; if a node currently being visited (&lt;code&gt;visiting&lt;/code&gt; state) is encountered again, a cycle exists, and an empty list is returned.&lt;/p&gt;
&lt;h3 id="c-implementation-dfs"&gt;C++ Implementation (DFS)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;list&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;algorithm&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // For std::reverse&lt;/span&gt;

&lt;span class="c1"&gt;// Using enum for visited states for clarity&lt;/span&gt;
&lt;span class="k"&gt;enum&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;State&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UNVISITED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;VISITING&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;VISITED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UNVISITED&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Acts as a stack for nodes&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UNVISITED&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{};&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Cycle detected, return empty vector&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;reverse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;begin&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Reverse to get topological order&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;private&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;VISITING&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Mark as visiting&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UNVISITED&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Propagate cycle detection&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;VISITING&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Cycle detected&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;VISITED&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Mark as visited&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt;   &lt;/span&gt;&lt;span class="c1"&gt;// Add to stack after all descendants are visited&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;// Example Usage&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example 1: Simple DAG&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// 0 -&amp;gt; 1&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// 0 -&amp;gt; 2&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// 1 -&amp;gt; 3&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// 2 -&amp;gt; 3&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;C++ DFS Topological Sort 1: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: e.g., 0 2 1 3 or 0 1 2 3&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example 2: More complex DAG&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// 5 -&amp;gt; 0, 5 -&amp;gt; 2&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// 4 -&amp;gt; 0, 4 -&amp;gt; 1&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// 2 -&amp;gt; 3&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// 3 -&amp;gt; 1&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;C++ DFS Topological Sort 2: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: e.g., 4 5 2 3 1 0&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example 3: Graph with a cycle (0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0)&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;C++ DFS Topological Sort with cycle: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;res3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Cycle detected, no topological sort.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: Cycle detected&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&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;h3 id="explanation-of-c-dfs-code"&gt;Explanation of C++ DFS Code&lt;/h3&gt;
&lt;p&gt;The C++ code uses &lt;code&gt;std::vector&amp;lt;std::list&amp;lt;int&amp;gt;&amp;gt;&lt;/code&gt; for the adjacency list and &lt;code&gt;std::vector&amp;lt;State&amp;gt;&lt;/code&gt; for tracking visited states (using an &lt;code&gt;enum&lt;/code&gt; for clarity). The &lt;code&gt;dfs&lt;/code&gt; function is similar to Python's, marking nodes as &lt;code&gt;VISITING&lt;/code&gt; upon entry and &lt;code&gt;VISITED&lt;/code&gt; upon exit, pushing them to &lt;code&gt;resultStack&lt;/code&gt;. Cycle detection logic is identical. Finally, &lt;code&gt;std::reverse&lt;/code&gt; is used on &lt;code&gt;resultStack&lt;/code&gt; to obtain the correct topological order.&lt;/p&gt;
&lt;h3 id="java-implementation-dfs"&gt;Java Implementation (DFS)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.*&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Using enum for visited states for clarity&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;enum&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;UNVISITED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;VISITING&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;VISITED&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Arrays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;fill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;UNVISITED&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Stack&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Stack&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Stack for nodes&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;UNVISITED&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Cycle detected, return empty list&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Pop elements from stack to get topological order&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isEmpty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Stack&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;VISITING&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Mark as visiting&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;UNVISITED&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Propagate cycle detection&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;VISITING&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Cycle detected&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;visitedState&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;State&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;VISITED&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Mark as visited&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;resultStack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Add to stack after all descendants are visited&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example Usage&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Example 1: Simple DAG&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// 0 -&amp;gt; 1&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// 0 -&amp;gt; 2&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// 1 -&amp;gt; 3&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// 2 -&amp;gt; 3&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Java DFS Topological Sort 1: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: e.g., [0, 2, 1, 3] or [0, 1, 2, 3]&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Example 2: More complex DAG&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// 5 -&amp;gt; 0, 5 -&amp;gt; 2&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// 4 -&amp;gt; 0, 4 -&amp;gt; 1&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// 2 -&amp;gt; 3&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// 3 -&amp;gt; 1&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Java DFS Topological Sort 2: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: e.g., [4, 5, 2, 3, 1, 0]&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Example 3: Graph with a cycle (0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Java DFS Topological Sort with cycle: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;topologicalSortDFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: []&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="explanation-of-java-dfs-code"&gt;Explanation of Java DFS Code&lt;/h3&gt;
&lt;p&gt;The Java implementation mirrors the C++ and Python logic. It uses &lt;code&gt;List&amp;lt;List&amp;lt;Integer&amp;gt;&amp;gt;&lt;/code&gt; for the adjacency list and an array of &lt;code&gt;State&lt;/code&gt; enums for visited tracking. A &lt;code&gt;java.util.Stack&lt;/code&gt; is used to store the nodes. After the DFS traversal, elements are popped from the stack and added to an &lt;code&gt;ArrayList&lt;/code&gt; to obtain the final topological order. Cycle detection is handled identically to the other language examples.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="implementing-topological-sort-using-bfs-kahns-algorithm-in-python-c-and-java"&gt;Implementing Topological Sort using BFS (Kahn's Algorithm) in Python, C++, and Java&lt;/h2&gt;
&lt;p&gt;The BFS-based approach for topological sort, often known as Kahn's Algorithm, works on a different principle. It iteratively removes nodes that have no incoming edges (an in-degree of zero) and adds them to the topological order. When a node is removed, its outgoing edges are also "removed," which may reduce the in-degree of its neighbors to zero, making them eligible for the next step.&lt;/p&gt;
&lt;h3 id="understanding-kahns-algorithm"&gt;Understanding Kahn's Algorithm&lt;/h3&gt;
&lt;p&gt;Kahn's algorithm starts by finding all nodes that have an in-degree of zero. These nodes can be the first nodes in a topological sort because they don't depend on any other tasks. These nodes are added to a queue. The algorithm then proceeds as follows:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Dequeue a node &lt;code&gt;u&lt;/code&gt; from the queue and add it to the topological sort result.&lt;/li&gt;
&lt;li&gt;For each neighbor &lt;code&gt;v&lt;/code&gt; of &lt;code&gt;u&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;Decrement the in-degree of &lt;code&gt;v&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If the in-degree of &lt;code&gt;v&lt;/code&gt; becomes zero, enqueue &lt;code&gt;v&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This process continues until the queue is empty. If the number of nodes in the topological sort result is less than the total number of nodes in the graph, it implies that the graph contains a cycle.&lt;/p&gt;
&lt;h3 id="steps-for-bfs-based-topological-sort-kahns-algorithm"&gt;Steps for BFS-based Topological Sort (Kahn's Algorithm)&lt;/h3&gt;
&lt;p&gt;Here’s a step-by-step breakdown of how to implement topological sort using BFS:&lt;/p&gt;
&lt;h3 id="1-compute-in-degrees"&gt;1. Compute In-degrees&lt;/h3&gt;
&lt;p&gt;First, calculate the in-degree for every node in the graph. The in-degree of a node is the number of incoming edges it has.&lt;/p&gt;
&lt;h3 id="2-initialize-queue-with-zero-in-degree-nodes"&gt;2. Initialize Queue with Zero In-degree Nodes&lt;/h3&gt;
&lt;p&gt;Create a queue and add all nodes with an in-degree of zero to it. These are the starting points for the topological sort.&lt;/p&gt;
&lt;h3 id="3-process-queue"&gt;3. Process Queue&lt;/h3&gt;
&lt;p&gt;While the queue is not empty:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;*   Dequeue a node `u`.
*   Add `u` to your topological sort result list.
*   For each neighbor `v` of `u`:
    *   Decrement the in-degree of `v`.
    *   If the in-degree of `v` becomes zero, enqueue `v`.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="4-check-for-cycles"&gt;4. Check for Cycles&lt;/h3&gt;
&lt;p&gt;After the loop finishes, compare the count of nodes in your result list with the total number of nodes in the graph. If they are not equal, it means there was a cycle in the graph, and a topological sort is not possible.&lt;/p&gt;
&lt;h3 id="python-implementation-bfs-kahns-algorithm"&gt;Python Implementation (BFS - Kahn's Algorithm)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;collections&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;defaultdict&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;in_degree&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;numVertices&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;u&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="n"&gt;in_degree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

        &lt;span class="n"&gt;queue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;in_degree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="n"&gt;count_visited_nodes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;u&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;popleft&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;count_visited_nodes&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="n"&gt;in_degree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;in_degree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# If count_visited_nodes is not equal to numVertices, a cycle exists&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;count_visited_nodes&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt; &lt;span class="c1"&gt;# Cycle detected&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;

&lt;span class="c1"&gt;# Example Usage&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="vm"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;__main__&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;solver&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

    &lt;span class="c1"&gt;# Example 1: Simple DAG&lt;/span&gt;
    &lt;span class="n"&gt;numVertices1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;defaultdict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Python BFS Topological Sort 1: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Expected: e.g., [0, 1, 2, 3] or [0, 2, 1, 3]&lt;/span&gt;

    &lt;span class="c1"&gt;# Example 2: More complex DAG&lt;/span&gt;
    &lt;span class="n"&gt;numVertices2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;defaultdict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Python BFS Topological Sort 2: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Expected: e.g., [4, 5, 0, 2, 3, 1]&lt;/span&gt;

    &lt;span class="c1"&gt;# Example 3: Graph with a cycle (0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0)&lt;/span&gt;
    &lt;span class="n"&gt;numVertices3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;
    &lt;span class="n"&gt;adj3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;defaultdict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Python BFS Topological Sort with cycle: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Expected: []&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="explanation-of-python-bfs-code"&gt;Explanation of Python BFS Code&lt;/h3&gt;
&lt;p&gt;The Python code first initializes an &lt;code&gt;in_degree&lt;/code&gt; list for all vertices by iterating through the adjacency list. It then populates a &lt;code&gt;deque&lt;/code&gt; (which acts as a queue) with all vertices having an in-degree of 0. The main &lt;code&gt;while&lt;/code&gt; loop processes nodes from the queue, adding them to the &lt;code&gt;result&lt;/code&gt; list and decrementing the in-degree of their neighbors. If a neighbor's in-degree drops to 0, it's enqueued. Finally, &lt;code&gt;count_visited_nodes&lt;/code&gt; is compared with &lt;code&gt;numVertices&lt;/code&gt; to detect cycles.&lt;/p&gt;
&lt;h3 id="c-implementation-bfs-kahns-algorithm"&gt;C++ Implementation (BFS - Kahn's Algorithm)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;list&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;queue&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;numeric&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // For std::iota (not used here, but good for range)&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Calculate in-degrees for all vertices&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;countVisitedNodes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;front&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;countVisitedNodes&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If countVisitedNodes is not equal to numVertices, a cycle exists&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;countVisitedNodes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{};&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Cycle detected&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;// Example Usage&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example 1: Simple DAG&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;C++ BFS Topological Sort 1: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: e.g., 0 1 2 3 or 0 2 1 3&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example 2: More complex DAG&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;C++ BFS Topological Sort 2: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: e.g., 4 5 0 2 3 1&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example 3: Graph with a cycle (0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0)&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;C++ BFS Topological Sort with cycle: &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;res3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Cycle detected, no topological sort.&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;res3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: Cycle detected&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&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;h3 id="explanation-of-c-bfs-code"&gt;Explanation of C++ BFS Code&lt;/h3&gt;
&lt;p&gt;The C++ code uses &lt;code&gt;std::vector&amp;lt;int&amp;gt;&lt;/code&gt; for &lt;code&gt;inDegree&lt;/code&gt; and &lt;code&gt;std::queue&amp;lt;int&amp;gt;&lt;/code&gt; for the BFS queue. The logic for calculating in-degrees, populating the initial queue, and processing nodes is identical to the Python version. It also checks &lt;code&gt;countVisitedNodes&lt;/code&gt; against &lt;code&gt;numVertices&lt;/code&gt; to determine if a cycle was present. If a cycle exists, an empty &lt;code&gt;std::vector&lt;/code&gt; is returned.&lt;/p&gt;
&lt;h3 id="java-implementation-bfs-kahns-algorithm"&gt;Java Implementation (BFS - Kahn's Algorithm)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.*&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Calculate in-degrees for all vertices&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Queue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;LinkedList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;offer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;countVisitedNodes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isEmpty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;poll&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;countVisitedNodes&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;offer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If countVisitedNodes is not equal to numVertices, a cycle exists&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;countVisitedNodes&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Cycle detected&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="c1"&gt;// Example Usage&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kd"&gt;static&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Example 1: Simple DAG&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Java BFS Topological Sort 1: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj1&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: e.g., [0, 1, 2, 3] or [0, 2, 1, 3]&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Example 2: More complex DAG&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Java BFS Topological Sort 2: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj2&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: e.g., [4, 5, 0, 2, 3, 1]&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Example 3: Graph with a cycle (0 -&amp;gt; 1 -&amp;gt; 2 -&amp;gt; 0)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;&amp;quot;Java BFS Topological Sort with cycle: &amp;quot;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;solver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;topologicalSortBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numVertices3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj3&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Expected: []&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="explanation-of-java-bfs-code"&gt;Explanation of Java BFS Code&lt;/h3&gt;
&lt;p&gt;The Java implementation uses &lt;code&gt;int[]&lt;/code&gt; for &lt;code&gt;inDegree&lt;/code&gt; and &lt;code&gt;java.util.Queue&lt;/code&gt; implemented by &lt;code&gt;java.util.LinkedList&lt;/code&gt; for the BFS queue. The overall structure and logic are identical to the Python and C++ versions, ensuring consistency across all three language examples. Cycle detection is performed by checking if &lt;code&gt;countVisitedNodes&lt;/code&gt; equals &lt;code&gt;numVertices&lt;/code&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="comparing-dfs-and-bfs-approaches-for-topological-sort"&gt;Comparing DFS and BFS Approaches for Topological Sort&lt;/h2&gt;
&lt;p&gt;Both DFS and BFS offer valid ways to compute a topological sort, but they approach the problem differently and have distinct characteristics. Understanding these differences can help you choose the most suitable algorithm for a given scenario.&lt;/p&gt;
&lt;h3 id="similarities"&gt;Similarities&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Result Validity:&lt;/strong&gt; Both algorithms produce a valid topological ordering if one exists.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cycle Detection:&lt;/strong&gt; Both inherently detect cycles within the graph, returning an indication that a topological sort is not possible.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; Generally, both have the same time complexity of O(V + E), where V is the number of vertices and E is the number of edges, as they visit each vertex and edge once.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; Both typically require O(V + E) space for graph representation, plus O(V) for visited states/in-degrees and the result list/stack/queue.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="differences"&gt;Differences&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Algorithm Paradigm:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;DFS-based:&lt;/strong&gt; A recursive approach that explores deeply into paths before backtracking. It relies on the post-order traversal property.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;BFS-based (Kahn's):&lt;/strong&gt; An iterative approach that works layer by layer, starting with nodes that have no prerequisites. It relies on in-degree counts.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Order of Output:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;DFS-based:&lt;/strong&gt; Produces a valid topological order by adding nodes to a stack &lt;em&gt;after&lt;/em&gt; all their dependents have been visited. The final list is then reversed. The specific order can depend on the order of adjacency list iteration.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;BFS-based:&lt;/strong&gt; Directly produces a valid topological order by processing nodes in increasing order of dependencies. The specific order can depend on the order in which nodes with zero in-degree are added to the queue.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ease of Implementation (Subjective):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;DFS can feel more natural for some due to its recursive nature.&lt;/li&gt;
&lt;li&gt;BFS (Kahn's) can feel more intuitive for dependency resolution as it explicitly tracks prerequisites via in-degrees.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dependency on Stack/Queue:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;DFS-based uses a recursion stack (implicit) or an explicit stack.&lt;/li&gt;
&lt;li&gt;BFS-based uses an explicit queue.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="when-to-use-which"&gt;When to Use Which?&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;DFS-based (Post-order Traversal):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Often preferred when recursion is natural for the problem or when you need to process nodes &lt;em&gt;after&lt;/em&gt; all their children.&lt;/li&gt;
&lt;li&gt;Can be slightly simpler to write for some experienced programmers due to its recursive elegance.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;BFS-based (Kahn's Algorithm):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Highly intuitive for "task scheduling" or "prerequisite solving" problems because it starts with tasks that have no dependencies.&lt;/li&gt;
&lt;li&gt;Can be more straightforward for beginners to reason about as it's less abstract than recursion.&lt;/li&gt;
&lt;li&gt;Explicitly provides an ordering that respects immediate dependencies without requiring reversal.&lt;/li&gt;
&lt;li&gt;Can be used to find &lt;em&gt;all&lt;/em&gt; possible topological sorts by branching whenever multiple nodes have an in-degree of zero.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Ultimately, the choice often comes down to personal preference or specific requirements where one approach might offer a slight performance edge in certain edge cases, though their asymptotic complexities are the same. Both are excellent tools for solving problems involving directed acyclic graphs.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the performance characteristics of algorithms is crucial for writing efficient code. Both DFS and BFS approaches for topological sort share similar complexities.&lt;/p&gt;
&lt;h3 id="time-complexity-ov-e"&gt;Time Complexity: O(V + E)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;V:&lt;/strong&gt; Number of vertices (nodes) in the graph.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;E:&lt;/strong&gt; Number of edges in the graph.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;DFS-based Approach:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Each vertex is visited exactly once.&lt;/li&gt;
&lt;li&gt;For each vertex, we iterate through its adjacency list to visit its neighbors. This means each edge is traversed exactly once.&lt;/li&gt;
&lt;li&gt;Therefore, the total time spent is proportional to the sum of vertices and edges.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;BFS-based Approach (Kahn's Algorithm):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Calculating in-degrees:&lt;/strong&gt; Requires iterating through all edges, which takes O(E) time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Initializing the queue:&lt;/strong&gt; Iterates through all vertices once to find those with zero in-degree, taking O(V) time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Main &lt;code&gt;while&lt;/code&gt; loop:&lt;/strong&gt; Each vertex is enqueued and dequeued exactly once. When a vertex &lt;code&gt;u&lt;/code&gt; is dequeued, we iterate through its outgoing edges. This means each edge is processed once (when we decrement the in-degree of &lt;code&gt;v&lt;/code&gt; for an edge &lt;code&gt;(u, v)&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Therefore, the total time spent is O(E) + O(V) + O(V + E) = O(V + E).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="space-complexity-ov-e"&gt;Space Complexity: O(V + E)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;V:&lt;/strong&gt; Number of vertices.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;E:&lt;/strong&gt; Number of edges.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;DFS-based Approach:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Adjacency List:&lt;/strong&gt; O(V + E) to store the graph.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;visited&lt;/code&gt; array/set:&lt;/strong&gt; O(V) to store the state of each vertex.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recursion Stack:&lt;/strong&gt; In the worst case (a long linear graph), the recursion stack depth can be O(V).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Result Stack/List:&lt;/strong&gt; O(V) to store the topological order.&lt;/li&gt;
&lt;li&gt;Total: O(V + E).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;BFS-based Approach (Kahn's Algorithm):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Adjacency List:&lt;/strong&gt; O(V + E) to store the graph.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;in_degree&lt;/code&gt; array:&lt;/strong&gt; O(V) to store the in-degree of each vertex.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Queue:&lt;/strong&gt; In the worst case, all vertices might be in the queue simultaneously, requiring O(V) space.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Result List:&lt;/strong&gt; O(V) to store the topological order.&lt;/li&gt;
&lt;li&gt;Total: O(V + E).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In summary, both methods are efficient for topological sorting, demonstrating linear time and space complexity relative to the size of the graph.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="common-mistakes-and-how-to-avoid-them"&gt;Common Mistakes and How to Avoid Them&lt;/h2&gt;
&lt;p&gt;Implementing graph algorithms like topological sort can be tricky. Here are some common pitfalls and strategies to avoid them:&lt;/p&gt;
&lt;h3 id="1-forgetting-cycle-detection"&gt;1. Forgetting Cycle Detection&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Assuming the input graph is always a DAG and not implementing a mechanism to detect cycles. If a cycle exists, a topological sort is impossible, and your algorithm might enter an infinite loop (DFS) or produce an incomplete result (BFS).
&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;DFS:&lt;/strong&gt; Use three states for nodes (unvisited, visiting, visited). If you encounter a &lt;code&gt;visiting&lt;/code&gt; node during traversal, a cycle is detected. Return an empty list or throw an error.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;BFS (Kahn's):&lt;/strong&gt; Keep a count of the nodes added to the topological sort. If this count is less than the total number of nodes at the end, a cycle exists. Return an empty list or throw an error.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-incorrect-in-degree-calculation-bfs"&gt;2. Incorrect In-degree Calculation (BFS)&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Miscalculating the in-degrees, especially in graphs with disconnected components or multiple edges between nodes.
&lt;strong&gt;Solution:&lt;/strong&gt; Ensure you iterate through all nodes and their adjacency lists correctly to precisely sum up incoming edges for each vertex. A dedicated loop to populate the &lt;code&gt;in_degree&lt;/code&gt; array at the beginning is crucial. Double-check your graph representation and how edges are defined.&lt;/p&gt;
&lt;h3 id="3-not-handling-disconnected-components"&gt;3. Not Handling Disconnected Components&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Only starting the DFS or BFS from node 0 and assuming the graph is connected. If the graph has multiple disconnected components, some nodes might be missed.
&lt;strong&gt;Solution:&lt;/strong&gt; In the main calling function, iterate through all possible nodes from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;numVertices-1&lt;/code&gt;. If a node hasn't been visited (for DFS) or processed (for BFS as part of in-degree calculations), initiate a traversal from it. This ensures all parts of the graph are covered.&lt;/p&gt;
&lt;h3 id="4-graph-representation-errors"&gt;4. Graph Representation Errors&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Incorrectly building the adjacency list, leading to missed edges or erroneous connections. Forgetting that a directed edge &lt;code&gt;(u, v)&lt;/code&gt; means &lt;code&gt;u&lt;/code&gt; points to &lt;code&gt;v&lt;/code&gt;, and &lt;code&gt;v&lt;/code&gt; is a neighbor of &lt;code&gt;u&lt;/code&gt; (not vice-versa).
&lt;strong&gt;Solution:&lt;/strong&gt; Carefully construct your adjacency list based on the problem's definition of directed edges. Remember that for an edge &lt;code&gt;u -&amp;gt; v&lt;/code&gt;, &lt;code&gt;v&lt;/code&gt; should be added to &lt;code&gt;adj[u]&lt;/code&gt;. For BFS, also ensure &lt;code&gt;in_degree[v]&lt;/code&gt; is incremented.&lt;/p&gt;
&lt;h3 id="5-off-by-one-errors-in-indexing"&gt;5. Off-by-One Errors in Indexing&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake:&lt;/strong&gt; Common in languages like C++ and Java, misusing array sizes or loop boundaries, especially when dealing with &lt;code&gt;numVertices&lt;/code&gt; and 0-indexed arrays.
&lt;strong&gt;Solution:&lt;/strong&gt; Always be mindful of whether nodes are 0-indexed or 1-indexed and adjust array sizes and loop conditions accordingly. For &lt;code&gt;numVertices&lt;/code&gt; nodes (0 to &lt;code&gt;numVertices-1&lt;/code&gt;), arrays should be of size &lt;code&gt;numVertices&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="6-incorrect-dfs-post-order-processing"&gt;6. Incorrect DFS Post-order Processing&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Mistake (DFS):&lt;/strong&gt; Adding a node to the result list &lt;em&gt;before&lt;/em&gt; visiting all its children. This will lead to an incorrect topological order.
&lt;strong&gt;Solution:&lt;/strong&gt; In the DFS approach, a node should only be added to the result (or pushed onto the stack) &lt;em&gt;after&lt;/em&gt; the recursive calls for all its neighbors have returned and those subgraphs are fully explored. This is the definition of post-order traversal.&lt;/p&gt;
&lt;p&gt;By paying attention to these common issues and following the structured steps provided in this tutorial, you can confidently implement topological sort and avoid frustrating debugging sessions.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: Is the topological sort unique?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: No, for a given Directed Acyclic Graph (DAG), there can be multiple valid topological sorts. If two vertices have no direct path between them, their relative order in the sort can vary while still satisfying all dependency constraints.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Can topological sort be performed on a graph with cycles?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: No, topological sort is strictly defined for Directed Acyclic Graphs (DAGs). If a graph contains a cycle, no linear ordering can be found where all dependencies are satisfied, as a cycle implies a circular dependency.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: When should I use the DFS-based approach versus the BFS-based (Kahn's) approach?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Both approaches have the same time complexity and produce a valid sort. The DFS-based method (post-order traversal) is often intuitive for its recursive nature, while Kahn's Algorithm (BFS-based) explicitly tracks in-degrees and can be easier to conceptualize for dependency resolution, as it starts with tasks that have no prerequisites. The choice often comes down to personal preference or specific requirements.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Topological_sorting"&gt;Wikipedia: Topological sorting&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/topological-sorting/"&gt;GeeksforGeeks: Topological Sort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Depth-first_search"&gt;Wikipedia: Depth-first search&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Breadth-first_search"&gt;Wikipedia: Breadth-first search&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Graph Theory"/><category term="Python"/><category term="Graph Algorithms"/><category term="Sorting Algorithms"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/topological-sort-dfs-bfs-python-cpp-java.webp" width="1200"/><media:title type="plain">Topological Sort using DFS &amp; BFS in Python, C++, Java</media:title><media:description type="plain">Learn to implement topological sort using DFS and BFS algorithms across Python, C++, and Java. Master this critical graph algorithm for DAGs.</media:description></entry><entry><title>Leetcode: 269 - Alien Dictionary Code in Python, Java, C++</title><link href="https://analyticsdrive.tech/leetcode-269-alien-dictionary-code-python-java-cpp/" rel="alternate"/><published>2026-02-23T23:16:00+05:30</published><updated>2026-04-21T04:43:51.519556+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-23:/leetcode-269-alien-dictionary-code-python-java-cpp/</id><summary type="html">&lt;p&gt;Master Leetcode 269: Alien Dictionary. Learn to implement this challenging graph problem using topological sort with code examples in Python, Java, and C++.&lt;/p&gt;</summary><content type="html">&lt;p&gt;&lt;strong&gt;Leetcode: 269 - Alien Dictionary Code in Python, Java, C++&lt;/strong&gt; is a renowned and challenging problem that often appears in technical interviews for software development roles. It's a fantastic exercise in applying graph theory, specifically &lt;strong&gt;topological sort&lt;/strong&gt;, to reconstruct a sequence from partial orderings. This tutorial will guide you through understanding the problem, building the necessary graph structures, and implementing the solution in three popular programming languages: Python, Java, and C++. By the end, you'll have a solid grasp of how to tackle similar graph-based ordering problems.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#introduction-to-the-alien-dictionary-problem"&gt;Introduction to the Alien Dictionary Problem&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-solving-alien-dictionary"&gt;Prerequisites for Solving Alien Dictionary&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#graph-theory-basics"&gt;Graph Theory Basics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#adjacency-list-representation"&gt;Adjacency List Representation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#breadth-first-search-bfs-or-depth-first-search-dfs"&gt;Breadth-First Search (BFS) or Depth-First Search (DFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#basic-data-structures"&gt;Basic Data Structures&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#programming-language-fundamentals"&gt;Programming Language Fundamentals&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-the-problem-alien-dictionary-in-detail"&gt;Understanding the Problem: Alien Dictionary in Detail&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#key-observations"&gt;Key Observations:&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#core-concepts-graph-theory-and-topological-sort"&gt;Core Concepts: Graph Theory and Topological Sort&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#building-the-directed-graph"&gt;Building the Directed Graph&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#topological-sort-kahns-algorithm"&gt;Topological Sort (Kahn's Algorithm)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-by-step-solution-building-the-graph"&gt;Step-by-Step Solution: Building the Graph&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-1-gather-all-unique-characters-and-initialize-data-structures"&gt;Step 1: Gather All Unique Characters and Initialize Data Structures&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-2-extract-ordering-rules-edges"&gt;Step 2: Extract Ordering Rules (Edges)&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#compare-wrt-and-wrf"&gt;Compare "wrt" and "wrf":&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#compare-wrf-and-er"&gt;Compare "wrf" and "er":&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#compare-er-and-ett"&gt;Compare "er" and "ett":&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#compare-ett-and-rftt"&gt;Compare "ett" and "rftt":&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#current-state-of-graph"&gt;Current State of Graph&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-by-step-solution-performing-topological-sort"&gt;Step-by-Step Solution: Performing Topological Sort&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-1-initialize-queue-with-zero-in-degree-nodes"&gt;Step 1: Initialize Queue with Zero In-Degree Nodes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-2-process-queue"&gt;Step 2: Process Queue&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#iteration-1"&gt;Iteration 1:&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#iteration-2"&gt;Iteration 2:&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#iteration-3"&gt;Iteration 3:&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#iteration-4"&gt;Iteration 4:&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#iteration-5"&gt;Iteration 5:&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-3-check-for-cycle"&gt;Step 3: Check for Cycle&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-4-return-result"&gt;Step 4: Return Result&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#leetcode-269-alien-dictionary-code-in-python"&gt;Leetcode 269: Alien Dictionary Code in Python&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#python-code-explanation"&gt;Python Code Explanation:&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#leetcode-269-alien-dictionary-code-in-java"&gt;Leetcode 269: Alien Dictionary Code in Java&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#java-code-explanation"&gt;Java Code Explanation:&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#leetcode-269-alien-dictionary-code-in-c"&gt;Leetcode 269: Alien Dictionary Code in C++&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#c-code-explanation"&gt;C++ Code Explanation:&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#complexity-analysis"&gt;Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-edge-cases"&gt;Common Mistakes and Edge Cases&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-incorrect-graph-construction"&gt;1. Incorrect Graph Construction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-failure-to-detect-invalid-input-orders-prefix-rule"&gt;2. Failure to Detect Invalid Input Orders (Prefix Rule)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-missing-cycle-detection"&gt;3. Missing Cycle Detection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-off-by-one-errors-in-loop-boundaries"&gt;4. Off-by-One Errors in Loop Boundaries&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-handling-empty-input"&gt;5. Handling Empty Input&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6-performance-considerations-for-adjacency-list"&gt;6. Performance Considerations for Adjacency List&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="introduction-to-the-alien-dictionary-problem"&gt;Introduction to the Alien Dictionary Problem&lt;/h2&gt;
&lt;p&gt;Imagine you've intercepted communications from an alien civilization, and you have a list of words from their dictionary, sorted lexicographically according to their unknown alphabet. Your task is to deduce the order of the letters in this alien alphabet. This is precisely what the &lt;strong&gt;Leetcode: 269 - Alien Dictionary&lt;/strong&gt; problem asks us to do. Given &lt;code&gt;words = ["wrt", "wrf", "er", "ett", "rftt"]&lt;/code&gt;, for example, we need to find an ordering like "wertf". This problem is considered hard because it requires not just recognizing the underlying graph structure but also correctly applying a topological sort algorithm to derive the final character order. Successfully solving this problem demonstrates a strong understanding of graph traversal and dependency management, crucial skills for any developer.&lt;/p&gt;
&lt;h2 id="prerequisites-for-solving-alien-dictionary"&gt;Prerequisites for Solving Alien Dictionary&lt;/h2&gt;
&lt;p&gt;Before diving into the solution for &lt;strong&gt;Leetcode: 269 - Alien Dictionary code in python java and c++&lt;/strong&gt;, ensure you have a foundational understanding of these core computer science concepts:&lt;/p&gt;
&lt;h3 id="graph-theory-basics"&gt;Graph Theory Basics&lt;/h3&gt;
&lt;p&gt;You should be familiar with what a graph is, including nodes (vertices) and edges. Understanding directed graphs (edges have a direction) and directed acyclic graphs (DAGs – directed graphs with no cycles) is crucial. The Alien Dictionary problem inherently translates into a DAG problem where characters are nodes and their orderings are directed edges.&lt;/p&gt;
&lt;h3 id="adjacency-list-representation"&gt;Adjacency List Representation&lt;/h3&gt;
&lt;p&gt;Knowing how to represent a graph using an adjacency list is fundamental. This typically involves using a dictionary (hash map) where keys are nodes and values are lists of their direct neighbors. This representation is efficient for adding edges and iterating through neighbors.&lt;/p&gt;
&lt;h3 id="breadth-first-search-bfs-or-depth-first-search-dfs"&gt;Breadth-First Search (BFS) or Depth-First Search (DFS)&lt;/h3&gt;
&lt;p&gt;Familiarity with these graph traversal algorithms is important. While we'll be using topological sort, both BFS and DFS form the basis of most graph algorithms, including the two primary methods for topological sort. Kahn's algorithm, which we will use, is BFS-based. For a deeper dive into another BFS application, consider &lt;a href="/01-matrix-problem-shortest-distance-bfs-dp-explained/"&gt;Unraveling the 01 Matrix: Finding the Nearest Zero with BFS and DP&lt;/a&gt;. If you're interested in DFS, exploring &lt;a href="/mastering-depth-first-search/"&gt;Mastering Depth-First Search (DFS)&lt;/a&gt; can be beneficial.&lt;/p&gt;
&lt;h3 id="basic-data-structures"&gt;Basic Data Structures&lt;/h3&gt;
&lt;p&gt;You'll need a good grasp of hash maps (dictionaries), sets, and queues. Hash maps are essential for storing graph nodes and their in-degrees, sets for keeping track of unique characters, and queues for implementing Kahn's algorithm.&lt;/p&gt;
&lt;h3 id="programming-language-fundamentals"&gt;Programming Language Fundamentals&lt;/h3&gt;
&lt;p&gt;Solid understanding of either Python, Java, or C++ syntax, data structures, and object-oriented concepts (if applicable) is necessary to follow the code examples and implement your own solution effectively. This includes handling strings, lists/arrays, and maps/dictionaries.&lt;/p&gt;
&lt;h2 id="understanding-the-problem-alien-dictionary-in-detail"&gt;Understanding the Problem: Alien Dictionary in Detail&lt;/h2&gt;
&lt;p&gt;The input to the Alien Dictionary problem is a list of strings, &lt;code&gt;words&lt;/code&gt;, representing words in an alien language, sorted lexicographically. This means if &lt;code&gt;wordA&lt;/code&gt; comes before &lt;code&gt;wordB&lt;/code&gt; in the list, then &lt;code&gt;wordA&lt;/code&gt; is lexicographically smaller than &lt;code&gt;wordB&lt;/code&gt; according to the alien alphabet.&lt;/p&gt;
&lt;p&gt;The goal is to return a string representing the alien alphabet's order. If no valid order can be determined (due to conflicting rules or cycles), an empty string should be returned.&lt;/p&gt;
&lt;h3 id="key-observations"&gt;Key Observations:&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Pairwise Comparisons:&lt;/strong&gt; The ordering information comes from comparing adjacent words. If &lt;code&gt;word1&lt;/code&gt; and &lt;code&gt;word2&lt;/code&gt; are consecutive in the input list, and they differ at some character position &lt;code&gt;i&lt;/code&gt;, then the character &lt;code&gt;word1[i]&lt;/code&gt; must come before &lt;code&gt;word2[i]&lt;/code&gt; in the alien alphabet.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;First Difference Matters:&lt;/strong&gt; Once a difference is found between two words, say &lt;code&gt;word1[i]&lt;/code&gt; != &lt;code&gt;word2[i]&lt;/code&gt;, then &lt;code&gt;word1[i]&lt;/code&gt; must precede &lt;code&gt;word2[i]&lt;/code&gt;. Any characters after this first difference in these two words provide no &lt;em&gt;new&lt;/em&gt; ordering information relative to each other.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prefix Rule:&lt;/strong&gt; If &lt;code&gt;word1&lt;/code&gt; is a prefix of &lt;code&gt;word2&lt;/code&gt; (e.g., "abc", "ab"), but &lt;code&gt;word2&lt;/code&gt; appears &lt;em&gt;before&lt;/em&gt; &lt;code&gt;word1&lt;/code&gt; in the input list, it's an invalid ordering and implies a cycle. However, if &lt;code&gt;word1&lt;/code&gt; is a prefix of &lt;code&gt;word2&lt;/code&gt; and &lt;code&gt;word1&lt;/code&gt; appears &lt;em&gt;before&lt;/em&gt; &lt;code&gt;word2&lt;/code&gt;, this provides no ordering information between &lt;code&gt;word1&lt;/code&gt; and &lt;code&gt;word2&lt;/code&gt; themselves but confirms consistency. If &lt;code&gt;word2&lt;/code&gt; is a prefix of &lt;code&gt;word1&lt;/code&gt; (e.g., "ab", "abc") and &lt;code&gt;word1&lt;/code&gt; appears after &lt;code&gt;word2&lt;/code&gt;, it's valid. The problem states words are sorted lexicographically. If &lt;code&gt;word1 = "apple"&lt;/code&gt; and &lt;code&gt;word2 = "app"&lt;/code&gt;, and &lt;code&gt;word1&lt;/code&gt; comes &lt;em&gt;before&lt;/em&gt; &lt;code&gt;word2&lt;/code&gt;, it's an invalid input (as "app" should be smaller than "apple"). We must detect this.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;All Characters:&lt;/strong&gt; We need to consider all unique characters present across &lt;em&gt;all&lt;/em&gt; words, even if some characters don't directly form an ordering pair. They might be part of the alphabet and appear in the final sorted order.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="core-concepts-graph-theory-and-topological-sort"&gt;Core Concepts: Graph Theory and Topological Sort&lt;/h2&gt;
&lt;p&gt;The Alien Dictionary problem is a perfect fit for a graph-based solution using topological sort. Let's break down why.&lt;/p&gt;
&lt;h3 id="building-the-directed-graph"&gt;Building the Directed Graph&lt;/h3&gt;
&lt;p&gt;Each unique character in the alien alphabet will be a &lt;strong&gt;node&lt;/strong&gt; (or vertex) in our graph. An ordering rule, such as 'a' must come before 'b', will be represented as a &lt;strong&gt;directed edge&lt;/strong&gt; from 'a' to 'b' (a -&amp;gt; b).&lt;/p&gt;
&lt;p&gt;To construct this graph:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialize:&lt;/strong&gt; Create a set to store all unique characters seen across all words. Create an adjacency list (e.g., &lt;code&gt;Map&amp;lt;Character, List&amp;lt;Character&amp;gt;&amp;gt;&lt;/code&gt;) to represent the graph and a map (e.g., &lt;code&gt;Map&amp;lt;Character, Integer&amp;gt;&lt;/code&gt;) to store the in-degree of each character. The in-degree of a node is the number of incoming edges it has.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Populate All Characters:&lt;/strong&gt; Iterate through all words and all characters within those words. Add each unique character to your set and initialize its in-degree to 0 in the in-degree map. Also, ensure each character has an entry in the adjacency list, even if its list of neighbors is initially empty.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Find Orderings (Edges):&lt;/strong&gt; Iterate through the &lt;code&gt;words&lt;/code&gt; list, comparing &lt;code&gt;word[i]&lt;/code&gt; with &lt;code&gt;word[i+1]&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;For each pair, iterate through their characters until you find the first position &lt;code&gt;j&lt;/code&gt; where &lt;code&gt;word[i][j]&lt;/code&gt; is different from &lt;code&gt;word[i+1][j]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Once a difference is found, &lt;code&gt;word[i][j]&lt;/code&gt; must come before &lt;code&gt;word[i+1][j]&lt;/code&gt;. Add a directed edge from &lt;code&gt;word[i][j]&lt;/code&gt; to &lt;code&gt;word[i+1][j]&lt;/code&gt; in your adjacency list. Increment the in-degree of &lt;code&gt;word[i+1][j]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Crucial Edge Case:&lt;/strong&gt; If &lt;code&gt;word[i+1]&lt;/code&gt; is a prefix of &lt;code&gt;word[i]&lt;/code&gt; (e.g., &lt;code&gt;words = ["abc", "ab"]&lt;/code&gt;), it implies an invalid lexicographical order, as "abc" should not precede "ab" if "ab" is a prefix of "abc". In this scenario, we must return an empty string, as a valid order cannot be determined. This check should occur &lt;em&gt;before&lt;/em&gt; finding any character differences if &lt;code&gt;word[i]&lt;/code&gt; is longer and &lt;code&gt;word[i+1]&lt;/code&gt; is its prefix.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="topological-sort-kahns-algorithm"&gt;Topological Sort (Kahn's Algorithm)&lt;/h3&gt;
&lt;p&gt;Once the graph is built, we apply topological sort. Kahn's algorithm (BFS-based) is particularly suitable here because it naturally handles cycle detection and produces a valid order efficiently.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialize Queue:&lt;/strong&gt; Add all characters (nodes) with an in-degree of 0 to a queue. These are the characters that have no dependencies (no characters must come before them).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Process Queue:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;While the queue is not empty:&lt;ul&gt;
&lt;li&gt;Dequeue a character &lt;code&gt;u&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Append &lt;code&gt;u&lt;/code&gt; to your result string/list.&lt;/li&gt;
&lt;li&gt;For each neighbor &lt;code&gt;v&lt;/code&gt; of &lt;code&gt;u&lt;/code&gt; (i.e., for every character &lt;code&gt;v&lt;/code&gt; that &lt;code&gt;u&lt;/code&gt; precedes):&lt;ul&gt;
&lt;li&gt;Decrement the in-degree of &lt;code&gt;v&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;v&lt;/code&gt;'s in-degree becomes 0, enqueue &lt;code&gt;v&lt;/code&gt;. This means &lt;code&gt;v&lt;/code&gt; no longer has any preceding dependencies that haven't been processed.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cycle Detection:&lt;/strong&gt; After the queue is empty, compare the length of your result string with the total number of unique characters initially present in the &lt;code&gt;words&lt;/code&gt;. If they are not equal, it means there was a cycle in the graph, and thus no valid topological order exists. In this case, return an empty string. Otherwise, return the constructed result string.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="step-by-step-solution-building-the-graph"&gt;Step-by-Step Solution: Building the Graph&lt;/h2&gt;
&lt;p&gt;Let's walk through the process of building the graph with an example: &lt;code&gt;words = ["wrt", "wrf", "er", "ett", "rftt"]&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="step-1-gather-all-unique-characters-and-initialize-data-structures"&gt;Step 1: Gather All Unique Characters and Initialize Data Structures&lt;/h3&gt;
&lt;p&gt;First, we iterate through all words to identify every unique character.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;'w'&lt;/code&gt;, &lt;code&gt;'r'&lt;/code&gt;, &lt;code&gt;'t'&lt;/code&gt;, &lt;code&gt;'f'&lt;/code&gt;, &lt;code&gt;'e'&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Initialize:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;adj = {}&lt;/code&gt; (adjacency list)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;in_degree = {}&lt;/code&gt; (in-degree map)&lt;/li&gt;
&lt;li&gt;For each unique char &lt;code&gt;c&lt;/code&gt;: &lt;code&gt;adj[c] = []&lt;/code&gt;, &lt;code&gt;in_degree[c] = 0&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;all_chars = {'w', 'r', 't', 'f', 'e'}&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-2-extract-ordering-rules-edges"&gt;Step 2: Extract Ordering Rules (Edges)&lt;/h3&gt;
&lt;p&gt;Now, compare adjacent words to find the first differing character.&lt;/p&gt;
&lt;h4 id="compare-wrt-and-wrf"&gt;Compare "wrt" and "wrf":&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;'w'&lt;/code&gt; == &lt;code&gt;'w'&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;'r'&lt;/code&gt; == &lt;code&gt;'r'&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;'t'&lt;/code&gt; != &lt;code&gt;'f'&lt;/code&gt;. This implies &lt;code&gt;t&lt;/code&gt; comes before &lt;code&gt;f&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Add edge: &lt;code&gt;t -&amp;gt; f&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;adj['t'].append('f')&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;in_degree['f'] += 1&lt;/code&gt; (Now &lt;code&gt;in_degree['f'] = 1&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="compare-wrf-and-er"&gt;Compare "wrf" and "er":&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;'w'&lt;/code&gt; != &lt;code&gt;'e'&lt;/code&gt;. This implies &lt;code&gt;w&lt;/code&gt; comes before &lt;code&gt;e&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Add edge: &lt;code&gt;w -&amp;gt; e&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;adj['w'].append('e')&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;in_degree['e'] += 1&lt;/code&gt; (Now &lt;code&gt;in_degree['e'] = 1&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="compare-er-and-ett"&gt;Compare "er" and "ett":&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;'e'&lt;/code&gt; == &lt;code&gt;'e'&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;'r'&lt;/code&gt; != &lt;code&gt;'t'&lt;/code&gt;. This implies &lt;code&gt;r&lt;/code&gt; comes before &lt;code&gt;t&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Add edge: &lt;code&gt;r -&amp;gt; t&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;adj['r'].append('t')&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;in_degree['t'] += 1&lt;/code&gt; (Now &lt;code&gt;in_degree['t'] = 1&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="compare-ett-and-rftt"&gt;Compare "ett" and "rftt":&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;'e'&lt;/code&gt; != &lt;code&gt;'r'&lt;/code&gt;. This implies &lt;code&gt;e&lt;/code&gt; comes before &lt;code&gt;r&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Add edge: &lt;code&gt;e -&amp;gt; r&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;adj['e'].append('r')&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;in_degree['r'] += 1&lt;/code&gt; (Now &lt;code&gt;in_degree['r'] = 1&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="current-state-of-graph"&gt;Current State of Graph&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;adj = { 'w': ['e'], 'r': ['t'], 't': ['f'], 'e': ['r'], 'f': [] }&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;in_degree = { 'w': 0, 'r': 1, 't': 1, 'f': 1, 'e': 1 }&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;all_chars = {'w', 'r', 't', 'f', 'e'}&lt;/code&gt; (total 5 unique characters)&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="step-by-step-solution-performing-topological-sort"&gt;Step-by-Step Solution: Performing Topological Sort&lt;/h2&gt;
&lt;p&gt;Now, using Kahn's algorithm (BFS-based) for the topological sort.&lt;/p&gt;
&lt;h3 id="step-1-initialize-queue-with-zero-in-degree-nodes"&gt;Step 1: Initialize Queue with Zero In-Degree Nodes&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Scan &lt;code&gt;in_degree&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;'w'&lt;/code&gt; has &lt;code&gt;in_degree = 0&lt;/code&gt;. Add &lt;code&gt;'w'&lt;/code&gt; to queue.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;queue = ['w']&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;result = []&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-2-process-queue"&gt;Step 2: Process Queue&lt;/h3&gt;
&lt;h4 id="iteration-1"&gt;Iteration 1:&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Dequeue &lt;code&gt;'w'&lt;/code&gt;. &lt;code&gt;result = ['w']&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Neighbors of &lt;code&gt;'w'&lt;/code&gt;: &lt;code&gt;['e']&lt;/code&gt;&lt;ul&gt;
&lt;li&gt;Decrement &lt;code&gt;in_degree['e']&lt;/code&gt;. &lt;code&gt;in_degree['e']&lt;/code&gt; becomes 0.&lt;/li&gt;
&lt;li&gt;Enqueue &lt;code&gt;'e'&lt;/code&gt;. &lt;code&gt;queue = ['e']&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="iteration-2"&gt;Iteration 2:&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Dequeue &lt;code&gt;'e'&lt;/code&gt;. &lt;code&gt;result = ['w', 'e']&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Neighbors of &lt;code&gt;'e'&lt;/code&gt;: &lt;code&gt;['r']&lt;/code&gt;&lt;ul&gt;
&lt;li&gt;Decrement &lt;code&gt;in_degree['r']&lt;/code&gt;. &lt;code&gt;in_degree['r']&lt;/code&gt; becomes 0.&lt;/li&gt;
&lt;li&gt;Enqueue &lt;code&gt;'r'&lt;/code&gt;. &lt;code&gt;queue = ['r']&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="iteration-3"&gt;Iteration 3:&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Dequeue &lt;code&gt;'r'&lt;/code&gt;. &lt;code&gt;result = ['w', 'e', 'r']&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Neighbors of &lt;code&gt;'r'&lt;/code&gt;: &lt;code&gt;['t']&lt;/code&gt;&lt;ul&gt;
&lt;li&gt;Decrement &lt;code&gt;in_degree['t']&lt;/code&gt;. &lt;code&gt;in_degree['t']&lt;/code&gt; becomes 0.&lt;/li&gt;
&lt;li&gt;Enqueue &lt;code&gt;'t'&lt;/code&gt;. &lt;code&gt;queue = ['t']&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="iteration-4"&gt;Iteration 4:&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Dequeue &lt;code&gt;'t'&lt;/code&gt;. &lt;code&gt;result = ['w', 'e', 'r', 't']&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Neighbors of &lt;code&gt;'t'&lt;/code&gt;: &lt;code&gt;['f']&lt;/code&gt;&lt;ul&gt;
&lt;li&gt;Decrement &lt;code&gt;in_degree['f']&lt;/code&gt;. &lt;code&gt;in_degree['f']&lt;/code&gt; becomes 0.&lt;/li&gt;
&lt;li&gt;Enqueue &lt;code&gt;'f'&lt;/code&gt;. &lt;code&gt;queue = ['f']&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="iteration-5"&gt;Iteration 5:&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Dequeue &lt;code&gt;'f'&lt;/code&gt;. &lt;code&gt;result = ['w', 'e', 'r', 't', 'f']&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Neighbors of &lt;code&gt;'f'&lt;/code&gt;: &lt;code&gt;[]&lt;/code&gt; (none)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;queue = []&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-3-check-for-cycle"&gt;Step 3: Check for Cycle&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;len(result)&lt;/code&gt; (which is 5) == &lt;code&gt;len(all_chars)&lt;/code&gt; (which is 5).&lt;/li&gt;
&lt;li&gt;No cycle detected.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-4-return-result"&gt;Step 4: Return Result&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Join &lt;code&gt;result&lt;/code&gt;: &lt;code&gt;"wertf"&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This detailed walkthrough illustrates how the graph is constructed and then traversed using Kahn's algorithm to obtain the correct alien alphabet order.&lt;/p&gt;
&lt;h2 id="leetcode-269-alien-dictionary-code-in-python"&gt;Leetcode 269: Alien Dictionary Code in Python&lt;/h2&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;collections&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;alienOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Step 1: Initialize data structures for graph and in-degrees&lt;/span&gt;
        &lt;span class="c1"&gt;# all_chars: A set to store all unique characters encountered across all words.&lt;/span&gt;
        &lt;span class="c1"&gt;# adj: An adjacency list (graph) where adj[u] is a list of characters that &amp;#39;u&amp;#39; must precede.&lt;/span&gt;
        &lt;span class="c1"&gt;# in_degree: A map where in_degree[c] is the count of characters that must precede &amp;#39;c&amp;#39;.&lt;/span&gt;
        &lt;span class="n"&gt;all_chars&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="n"&gt;adj&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;collections&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;defaultdict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;in_degree&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;collections&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;defaultdict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Populate all_chars and initialize in_degrees for all characters to 0&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;word&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;char_code&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;all_chars&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char_code&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;in_degree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;char_code&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="c1"&gt;# Initialize all to 0, will be updated as edges are added&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 2: Build the graph by comparing adjacent words&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="n"&gt;word1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
            &lt;span class="n"&gt;word2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

            &lt;span class="c1"&gt;# Critical Edge Case: If word2 is a prefix of word1 (e.g., [&amp;quot;abc&amp;quot;, &amp;quot;ab&amp;quot;]), it&amp;#39;s an invalid input.&lt;/span&gt;
            &lt;span class="c1"&gt;# This indicates an inconsistent lexicographical order.&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;startswith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;&amp;quot;&lt;/span&gt;

            &lt;span class="c1"&gt;# Find the first differing character&lt;/span&gt;
            &lt;span class="n"&gt;min_len&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
            &lt;span class="n"&gt;found_diff&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;min_len&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="n"&gt;char1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="n"&gt;char2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;char1&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="c1"&gt;# Found an ordering rule: char1 must come before char2&lt;/span&gt;
                    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;char2&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;char1&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt; &lt;span class="c1"&gt;# Avoid duplicate edges&lt;/span&gt;
                        &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;char1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                        &lt;span class="n"&gt;in_degree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                    &lt;span class="n"&gt;found_diff&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
                    &lt;span class="k"&gt;break&lt;/span&gt;
            &lt;span class="c1"&gt;# If no difference found until min_len, it means one word is a prefix of the other.&lt;/span&gt;
            &lt;span class="c1"&gt;# The edge case check above handles word2 being a prefix of word1.&lt;/span&gt;
            &lt;span class="c1"&gt;# If word1 is a prefix of word2 (e.g. &amp;quot;abc&amp;quot;, &amp;quot;abcd&amp;quot;), no ordering info is obtained from this pair,&lt;/span&gt;
            &lt;span class="c1"&gt;# which is fine.&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 3: Perform Topological Sort using Kahn&amp;#39;s Algorithm (BFS)&lt;/span&gt;
        &lt;span class="c1"&gt;# Queue for BFS, initially contains all characters with an in-degree of 0.&lt;/span&gt;
        &lt;span class="n"&gt;queue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;collections&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;deque&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;char_code&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;char_code&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;all_chars&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;in_degree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;char_code&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt; &lt;span class="c1"&gt;# Stores the sorted characters&lt;/span&gt;

        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;u&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;popleft&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

            &lt;span class="c1"&gt;# For each neighbor &amp;#39;v&amp;#39; of &amp;#39;u&amp;#39;:&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                &lt;span class="n"&gt;in_degree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Decrement in-degree of &amp;#39;v&amp;#39;&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;in_degree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# If in-degree becomes 0, &amp;#39;v&amp;#39; has no more prerequisites, add to queue&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 4: Check for cycles&lt;/span&gt;
        &lt;span class="c1"&gt;# If the length of the result string is less than the total number of unique characters,&lt;/span&gt;
        &lt;span class="c1"&gt;# it means there was a cycle in the graph, and a valid topological order cannot be formed.&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;all_chars&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;&amp;quot;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="python-code-explanation"&gt;Python Code Explanation:&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; &lt;code&gt;all_chars&lt;/code&gt; set gathers all unique characters. &lt;code&gt;adj&lt;/code&gt; is a &lt;code&gt;defaultdict(list)&lt;/code&gt; for the adjacency list (graph), and &lt;code&gt;in_degree&lt;/code&gt; is a &lt;code&gt;defaultdict(int)&lt;/code&gt; to store in-degrees. All characters are added to &lt;code&gt;all_chars&lt;/code&gt; and their &lt;code&gt;in_degree&lt;/code&gt; initialized to 0.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graph Construction:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;It iterates through adjacent pairs of words &lt;code&gt;(words[i], words[i+1])&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prefix Check:&lt;/strong&gt; A critical check ensures &lt;code&gt;word2&lt;/code&gt; is not a prefix of &lt;code&gt;word1&lt;/code&gt; if &lt;code&gt;len(word1) &amp;gt; len(word2)&lt;/code&gt;. This indicates an invalid input order, so we return &lt;code&gt;""&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;It finds the first differing character &lt;code&gt;char1&lt;/code&gt; from &lt;code&gt;word1&lt;/code&gt; and &lt;code&gt;char2&lt;/code&gt; from &lt;code&gt;word2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;An edge &lt;code&gt;char1 -&amp;gt; char2&lt;/code&gt; is added to &lt;code&gt;adj&lt;/code&gt;, and &lt;code&gt;in_degree[char2]&lt;/code&gt; is incremented. &lt;code&gt;if char2 not in adj[char1]&lt;/code&gt; prevents duplicate edges, which is important for correct in-degree counts.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Topological Sort (Kahn's):&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;A &lt;code&gt;deque&lt;/code&gt; (double-ended queue) is used for the BFS queue. It's initialized with all characters that have an &lt;code&gt;in_degree&lt;/code&gt; of 0.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;while queue&lt;/code&gt; loop processes characters. &lt;code&gt;u&lt;/code&gt; is dequeued, added to &lt;code&gt;result&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For each neighbor &lt;code&gt;v&lt;/code&gt; of &lt;code&gt;u&lt;/code&gt;, &lt;code&gt;in_degree[v]&lt;/code&gt; is decremented. If &lt;code&gt;in_degree[v]&lt;/code&gt; becomes 0, &lt;code&gt;v&lt;/code&gt; is enqueued.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cycle Detection:&lt;/strong&gt; After the BFS, if &lt;code&gt;len(result)&lt;/code&gt; is not equal to &lt;code&gt;len(all_chars)&lt;/code&gt;, it implies a cycle was present, and an empty string is returned.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Return:&lt;/strong&gt; Finally, &lt;code&gt;"".join(result)&lt;/code&gt; constructs the alien alphabet string.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="leetcode-269-alien-dictionary-code-in-java"&gt;Leetcode 269: Alien Dictionary Code in Java&lt;/h2&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nn"&gt;java.util.*&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="kd"&gt;public&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nf"&gt;alienOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 1: Initialize data structures for graph and in-degrees&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// allChars: A set to store all unique characters encountered.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// adj: Adjacency list (graph) where adj.get(u) is a list of characters &amp;#39;u&amp;#39; must precede.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// inDegree: A map where inDegree.get(c) is the count of characters that must precede &amp;#39;c&amp;#39;.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Set&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;allChars&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;HashSet&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Populate allChars and initialize inDegrees for all characters to 0&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toCharArray&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;allChars&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;putIfAbsent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Ensure all chars are graph nodes&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;putIfAbsent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Initialize all to 0&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 2: Build the graph by comparing adjacent words&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Critical Edge Case: If word2 is a prefix of word1 (e.g., [&amp;quot;abc&amp;quot;, &amp;quot;ab&amp;quot;]), it&amp;#39;s an invalid input.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// This indicates an inconsistent lexicographical order.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;startsWith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Find the first differing character&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;minLen&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;boolean&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;foundDiff&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;minLen&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;char1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;charAt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// Found an ordering rule: char1 must come before char2&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// Add edge char1 -&amp;gt; char2 to adjacency list&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// Only add if not already present to avoid duplicate edges and incorrect in-degree counts&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char1&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// This check can be slow for large graphs.&lt;/span&gt;
&lt;span class="w"&gt;                                                            &lt;/span&gt;&lt;span class="c1"&gt;// A Set&amp;lt;Character&amp;gt; for values in adj.get(char1) would be faster&lt;/span&gt;
&lt;span class="w"&gt;                                                            &lt;/span&gt;&lt;span class="c1"&gt;// or checking if inDegree count increased after adding.&lt;/span&gt;
&lt;span class="w"&gt;                        &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char1&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                        &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;foundDiff&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;break&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// If no difference found and word1 is a prefix of word2 (e.g. &amp;quot;abc&amp;quot;, &amp;quot;abcd&amp;quot;), no ordering info is obtained.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// The edge case above handles word2 being a prefix of word1.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 3: Perform Topological Sort using Kahn&amp;#39;s Algorithm (BFS)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;Queue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Character&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;LinkedList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Add all characters with an in-degree of 0 to the queue&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;allChars&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;offer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;StringBuilder&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;StringBuilder&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Stores the sorted characters&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isEmpty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;poll&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// For each neighbor &amp;#39;v&amp;#39; of &amp;#39;u&amp;#39;:&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Decrement in-degree of &amp;#39;v&amp;#39;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;offer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// If in-degree becomes 0, add &amp;#39;v&amp;#39; to queue&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 4: Check for cycles&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If the length of the result string is less than the total number of unique characters,&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// it means there was a cycle in the graph.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;allChars&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;size&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="java-code-explanation"&gt;Java Code Explanation:&lt;/h3&gt;
&lt;p&gt;The Java implementation mirrors the Python logic very closely.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; &lt;code&gt;HashSet&amp;lt;Character&amp;gt; allChars&lt;/code&gt;, &lt;code&gt;HashMap&amp;lt;Character, List&amp;lt;Character&amp;gt;&amp;gt; adj&lt;/code&gt;, &lt;code&gt;HashMap&amp;lt;Character, Integer&amp;gt; inDegree&lt;/code&gt;. &lt;code&gt;putIfAbsent&lt;/code&gt; is used to ensure all characters are initialized in the maps.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graph Construction:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;Similar loop structure for adjacent words.&lt;/li&gt;
&lt;li&gt;The prefix check &lt;code&gt;word1.length() &amp;gt; word2.length() &amp;amp;&amp;amp; word1.startsWith(word2)&lt;/code&gt; remains critical.&lt;/li&gt;
&lt;li&gt;When adding an edge, &lt;code&gt;!adj.get(char1).contains(char2)&lt;/code&gt; is used to prevent duplicate edges. For very large graphs or high-degree nodes, using &lt;code&gt;HashSet&amp;lt;Character&amp;gt;&lt;/code&gt; as the value in &lt;code&gt;adj&lt;/code&gt; would be more performant than &lt;code&gt;List&amp;lt;Character&amp;gt;&lt;/code&gt; for the &lt;code&gt;contains&lt;/code&gt; check.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Topological Sort:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;code&gt;LinkedList&lt;/code&gt; is used to implement the &lt;code&gt;Queue&lt;/code&gt; interface for BFS.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;offer()&lt;/code&gt; and &lt;code&gt;poll()&lt;/code&gt; methods are used for adding and removing elements from the queue.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;StringBuilder&lt;/code&gt; is used for efficient string concatenation.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cycle Detection:&lt;/strong&gt; Same logic: compare &lt;code&gt;result.length()&lt;/code&gt; with &lt;code&gt;allChars.size()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Return:&lt;/strong&gt; &lt;code&gt;result.toString()&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="leetcode-269-alien-dictionary-code-in-c"&gt;Leetcode 269: Alien Dictionary Code in C++&lt;/h2&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;string&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;unordered_map&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;unordered_set&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;queue&amp;gt;&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="cpf"&gt;&amp;lt;algorithm&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // For std::min and std::find&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;alienOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 1: Initialize data structures for graph and in-degrees&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// allChars: A set to store all unique characters encountered.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// adj: Adjacency list (graph) where adj[u] is a list of characters &amp;#39;u&amp;#39; must precede.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// inDegree: A map where inDegree[c] is the count of characters that must precede &amp;#39;c&amp;#39;.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;unordered_set&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;allChars&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;unordered_map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;unordered_map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Populate allChars and initialize inDegrees for all characters to 0&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;allChars&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Ensure char is in adj map, creates empty vector if not present&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Initialize all to 0&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 2: Build the graph by comparing adjacent words&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Critical Edge Case: If word2 is a prefix of word1 (e.g., {&amp;quot;abc&amp;quot;, &amp;quot;ab&amp;quot;}), it&amp;#39;s an invalid input.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// This indicates an inconsistent lexicographical order.&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rfind&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// rfind with 0 is like startsWith&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// Find the first differing character&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;minLen&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;foundDiff&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;minLen&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;char1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word1&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;word2&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// Found an ordering rule: char1 must come before char2&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// Add edge char1 -&amp;gt; char2 to adjacency list&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// Only add if not already present to avoid duplicate edges and incorrect in-degree counts&lt;/span&gt;

&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// Check if char2 is already a neighbor of char1.&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// This is O(N) where N is number of neighbors. For better performance&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// adj[char1] could be a std::unordered_set&amp;lt;char&amp;gt; instead of std::vector&amp;lt;char&amp;gt;&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="c1"&gt;// or we could track added edges in a separate set.&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighbors&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;char1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighbors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;begin&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighbors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;neighbors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                        &lt;/span&gt;&lt;span class="n"&gt;neighbors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;                        &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;char2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;foundDiff&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nb"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="k"&gt;break&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 3: Perform Topological Sort using Kahn&amp;#39;s Algorithm (BFS)&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Add all characters with an in-degree of 0 to the queue&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;allChars&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Stores the sorted characters&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;front&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="c1"&gt;// For each neighbor &amp;#39;v&amp;#39; of &amp;#39;u&amp;#39;:&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;adj&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;u&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// Decrement in-degree of &amp;#39;v&amp;#39;&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;inDegree&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;                    &lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="c1"&gt;// If in-degree becomes 0, add &amp;#39;v&amp;#39; to queue&lt;/span&gt;
&lt;span class="w"&gt;                &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// Step 4: Check for cycles&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// If the length of the result string is less than the total number of unique characters,&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="c1"&gt;// it means there was a cycle in the graph.&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;allChars&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="w"&gt;            &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="w"&gt;    &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;h3 id="c-code-explanation"&gt;C++ Code Explanation:&lt;/h3&gt;
&lt;p&gt;The C++ solution leverages standard library containers.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialization:&lt;/strong&gt; &lt;code&gt;std::unordered_set&amp;lt;char&amp;gt; allChars&lt;/code&gt;, &lt;code&gt;std::unordered_map&amp;lt;char, std::vector&amp;lt;char&amp;gt;&amp;gt; adj&lt;/code&gt;, &lt;code&gt;std::unordered_map&amp;lt;char, int&amp;gt; inDegree&lt;/code&gt;. Using &lt;code&gt;adj[c];&lt;/code&gt; automatically creates an empty &lt;code&gt;std::vector&amp;lt;char&amp;gt;&lt;/code&gt; if &lt;code&gt;c&lt;/code&gt; is not yet a key.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graph Construction:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;word1.rfind(word2, 0) == 0&lt;/code&gt; is the C++ equivalent for checking if &lt;code&gt;word1&lt;/code&gt; starts with &lt;code&gt;word2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;When adding an edge, &lt;code&gt;std::find&lt;/code&gt; is used to check for duplicates in the adjacency list. As noted in the comments, for performance-critical scenarios, &lt;code&gt;std::unordered_set&amp;lt;char&amp;gt;&lt;/code&gt; could be used for the values in &lt;code&gt;adj&lt;/code&gt; to ensure &lt;code&gt;O(1)&lt;/code&gt; average time for duplicate checks.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Topological Sort:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;&lt;code&gt;std::queue&amp;lt;char&amp;gt;&lt;/code&gt; is used for the BFS queue.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;push()&lt;/code&gt; and &lt;code&gt;pop()&lt;/code&gt; (after &lt;code&gt;front()&lt;/code&gt;) are used for queue operations.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;std::string result&lt;/code&gt; uses &lt;code&gt;push_back(u)&lt;/code&gt; to append characters.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cycle Detection:&lt;/strong&gt; Compares &lt;code&gt;result.length()&lt;/code&gt; with &lt;code&gt;allChars.size()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Return:&lt;/strong&gt; The &lt;code&gt;std::string result&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="complexity-analysis"&gt;Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the time and space complexity of the Alien Dictionary problem is crucial for evaluating its efficiency.&lt;/p&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;Let &lt;code&gt;N&lt;/code&gt; be the number of words in the input list, &lt;code&gt;L&lt;/code&gt; be the average length of a word, and &lt;code&gt;C&lt;/code&gt; be the total number of unique characters across all words (at most 26 for English alphabet, but could be larger for general characters).&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Gathering All Unique Characters and Initializing Data Structures:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Iterating through all words and their characters takes &lt;code&gt;O(N * L)&lt;/code&gt; time.&lt;/li&gt;
&lt;li&gt;Adding to &lt;code&gt;allChars&lt;/code&gt; set, &lt;code&gt;adj&lt;/code&gt; map, and &lt;code&gt;inDegree&lt;/code&gt; map: Each &lt;code&gt;insert&lt;/code&gt; or &lt;code&gt;put&lt;/code&gt; operation is &lt;code&gt;O(1)&lt;/code&gt; on average. Total &lt;code&gt;O(C)&lt;/code&gt; for initial setup for &lt;code&gt;C&lt;/code&gt; characters.&lt;/li&gt;
&lt;li&gt;Overall for initialization: &lt;code&gt;O(N * L)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Building the Graph:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We iterate through &lt;code&gt;N-1&lt;/code&gt; pairs of adjacent words.&lt;/li&gt;
&lt;li&gt;For each pair &lt;code&gt;(word1, word2)&lt;/code&gt;, we compare characters up to &lt;code&gt;min(len(word1), len(word2))&lt;/code&gt;, which is &lt;code&gt;O(L)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Adding an edge to the adjacency list and incrementing in-degree is &lt;code&gt;O(1)&lt;/code&gt; on average (assuming &lt;code&gt;std::vector::push_back&lt;/code&gt; or &lt;code&gt;List.add&lt;/code&gt; is amortized O(1)).&lt;/li&gt;
&lt;li&gt;The duplicate edge check (e.g., &lt;code&gt;!adj.get(char1).contains(char2)&lt;/code&gt; in Java or &lt;code&gt;std::find&lt;/code&gt; in C++) can be &lt;code&gt;O(C)&lt;/code&gt; in the worst case if &lt;code&gt;adj[char1]&lt;/code&gt; contains many neighbors. If using &lt;code&gt;Set&lt;/code&gt; for neighbors, this becomes &lt;code&gt;O(1)&lt;/code&gt; on average.&lt;/li&gt;
&lt;li&gt;In total, this step is &lt;code&gt;O(N * L)&lt;/code&gt; for comparing words. The graph can have at most &lt;code&gt;C&lt;/code&gt; nodes and &lt;code&gt;C*(C-1)&lt;/code&gt; edges in the worst case (though practically, usually much fewer distinct edges based on the input words). Let &lt;code&gt;E&lt;/code&gt; be the number of edges. Adding edges involves &lt;code&gt;N&lt;/code&gt; comparisons, each potentially adding one edge. Total for edges: &lt;code&gt;O(N*L + E)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Overall for building the graph: &lt;code&gt;O(N * L + E)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Topological Sort (Kahn's Algorithm):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Initializing the queue: &lt;code&gt;O(C)&lt;/code&gt; to iterate through all characters.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;while&lt;/code&gt; loop runs &lt;code&gt;C&lt;/code&gt; times (each character is dequeued once).&lt;/li&gt;
&lt;li&gt;Inside the loop:&lt;ul&gt;
&lt;li&gt;Dequeueing: &lt;code&gt;O(1)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Iterating through neighbors: Sum of &lt;code&gt;len(adj[u])&lt;/code&gt; for all &lt;code&gt;u&lt;/code&gt; is &lt;code&gt;O(E)&lt;/code&gt; (each edge is traversed once).&lt;/li&gt;
&lt;li&gt;Decrementing in-degree and enqueuing: &lt;code&gt;O(1)&lt;/code&gt; on average.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Overall for topological sort: &lt;code&gt;O(C + E)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Total Time Complexity:&lt;/strong&gt; &lt;code&gt;O(N * L + C + E)&lt;/code&gt;. Since &lt;code&gt;E&lt;/code&gt; is at most &lt;code&gt;N*L&lt;/code&gt; (we add at most one edge per word pair, bounded by length), and also &lt;code&gt;E&lt;/code&gt; is at most &lt;code&gt;C^2&lt;/code&gt;, it can be simplified. A tighter bound is &lt;code&gt;O(N * L + C^2)&lt;/code&gt; if &lt;code&gt;E&lt;/code&gt; is considered as the maximum number of unique edges. However, the most accurate is &lt;code&gt;O(N * L + E)&lt;/code&gt;, where &lt;code&gt;E&lt;/code&gt; is the number of distinct edges actually added. Given &lt;code&gt;C&lt;/code&gt; is at most 26, &lt;code&gt;C^2&lt;/code&gt; is small, so &lt;code&gt;O(N * L + E)&lt;/code&gt; effectively.&lt;/p&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;allChars&lt;/code&gt; set:&lt;/strong&gt; &lt;code&gt;O(C)&lt;/code&gt; to store all unique characters.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;adj&lt;/code&gt; (adjacency list):&lt;/strong&gt; &lt;code&gt;O(C + E)&lt;/code&gt; to store &lt;code&gt;C&lt;/code&gt; nodes and &lt;code&gt;E&lt;/code&gt; edges.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;inDegree&lt;/code&gt; map:&lt;/strong&gt; &lt;code&gt;O(C)&lt;/code&gt; to store in-degrees for all characters.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;queue&lt;/code&gt;:&lt;/strong&gt; In the worst case, the queue can hold all &lt;code&gt;C&lt;/code&gt; characters: &lt;code&gt;O(C)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;result&lt;/code&gt; string/StringBuilder:&lt;/strong&gt; &lt;code&gt;O(C)&lt;/code&gt; for the final alphabet order.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Total Space Complexity:&lt;/strong&gt; &lt;code&gt;O(C + E)&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="common-mistakes-and-edge-cases"&gt;Common Mistakes and Edge Cases&lt;/h2&gt;
&lt;p&gt;Solving the Alien Dictionary problem requires careful attention to various scenarios. Missing these can lead to incorrect solutions or runtime errors.&lt;/p&gt;
&lt;h3 id="1-incorrect-graph-construction"&gt;1. Incorrect Graph Construction&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Duplicate Edges:&lt;/strong&gt; If you add the same edge multiple times (e.g., &lt;code&gt;t -&amp;gt; f&lt;/code&gt; derived from &lt;code&gt;("wrt", "wrf")&lt;/code&gt; and again from &lt;code&gt;("ert", "erf")&lt;/code&gt;), the &lt;code&gt;in_degree&lt;/code&gt; count for &lt;code&gt;f&lt;/code&gt; will be inflated. This can prevent &lt;code&gt;f&lt;/code&gt; from ever reaching an in-degree of 0, leading to an incorrect result (e.g., &lt;code&gt;f&lt;/code&gt; might be omitted or a cycle might be falsely detected). Always check if an edge already exists before adding it and incrementing &lt;code&gt;in_degree&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Missing Characters:&lt;/strong&gt; Ensure &lt;em&gt;all&lt;/em&gt; unique characters from &lt;em&gt;all&lt;/em&gt; words are included in your graph and &lt;code&gt;in_degree&lt;/code&gt; map, even if they don't explicitly form an ordering pair. Some characters might be part of the alphabet but only appear in isolated words. Their in-degree should be initialized to 0.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="2-failure-to-detect-invalid-input-orders-prefix-rule"&gt;2. Failure to Detect Invalid Input Orders (Prefix Rule)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Example:&lt;/strong&gt; &lt;code&gt;words = ["abc", "ab"]&lt;/code&gt;. If "abc" comes before "ab" in a lexicographically sorted list, it implies an invalid ordering in the alien dictionary. This specific case &lt;em&gt;must&lt;/em&gt; be handled by immediately returning an empty string. The logic should be: if &lt;code&gt;word1&lt;/code&gt; is longer than &lt;code&gt;word2&lt;/code&gt;, and &lt;code&gt;word1&lt;/code&gt; starts with &lt;code&gt;word2&lt;/code&gt; (i.e., &lt;code&gt;word2&lt;/code&gt; is a prefix of &lt;code&gt;word1&lt;/code&gt;), and &lt;code&gt;word1&lt;/code&gt; appears before &lt;code&gt;word2&lt;/code&gt;, it's an invalid input.&lt;/li&gt;
&lt;li&gt;The check &lt;code&gt;if len(word1) &amp;gt; len(word2) and word1.startswith(word2): return ""&lt;/code&gt; in Python (and equivalents in Java/C++) addresses this directly before comparing characters.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="3-missing-cycle-detection"&gt;3. Missing Cycle Detection&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;A topological sort can only exist in a Directed Acyclic Graph (DAG). If the input words imply a cycle (e.g., &lt;code&gt;a &amp;lt; b&lt;/code&gt;, &lt;code&gt;b &amp;lt; c&lt;/code&gt;, and &lt;code&gt;c &amp;lt; a&lt;/code&gt;), no valid alphabet order exists.&lt;/li&gt;
&lt;li&gt;Kahn's algorithm naturally detects cycles: if the number of characters processed in the topological sort (&lt;code&gt;len(result)&lt;/code&gt;) is less than the total number of unique characters (&lt;code&gt;len(all_chars)&lt;/code&gt;), a cycle is present. In this case, return an empty string.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="4-off-by-one-errors-in-loop-boundaries"&gt;4. Off-by-One Errors in Loop Boundaries&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;When comparing adjacent words, the loop should go from &lt;code&gt;i&lt;/code&gt; to &lt;code&gt;len(words) - 2&lt;/code&gt; (or &lt;code&gt;len(words) - 1&lt;/code&gt; with &lt;code&gt;&amp;lt;&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;When comparing characters within words, the loop should go up to &lt;code&gt;min(len(word1), len(word2)) - 1&lt;/code&gt; (or &lt;code&gt;&amp;lt; min_len&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="5-handling-empty-input"&gt;5. Handling Empty Input&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;words&lt;/code&gt; is empty, an empty string should be returned. The provided solutions will correctly return an empty string for this edge case.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;words&lt;/code&gt; contains only one word (e.g., &lt;code&gt;["abc"]&lt;/code&gt;), all unique characters from that word should be returned in any order (usually lexicographical, but any order is valid). The current solution correctly handles this by putting all characters with in-degree 0 into the queue and returning them.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="6-performance-considerations-for-adjacency-list"&gt;6. Performance Considerations for Adjacency List&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;In Java and C++, checking &lt;code&gt;adj.get(char1).contains(char2)&lt;/code&gt; or &lt;code&gt;std::find(neighbors.begin(), neighbors.end(), char2)&lt;/code&gt; can be &lt;code&gt;O(C)&lt;/code&gt; in the worst case if a node has many neighbors. If the number of unique characters &lt;code&gt;C&lt;/code&gt; is large, this could degrade performance. For alphabets larger than 26, consider using &lt;code&gt;HashSet&amp;lt;Character&amp;gt;&lt;/code&gt; or &lt;code&gt;unordered_set&amp;lt;char&amp;gt;&lt;/code&gt; for the values in your adjacency map to ensure &lt;code&gt;O(1)&lt;/code&gt; average time for duplicate checks. For &lt;code&gt;C=26&lt;/code&gt;, a &lt;code&gt;List&lt;/code&gt; or &lt;code&gt;vector&lt;/code&gt; is typically acceptable.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;By carefully considering these common pitfalls and edge cases, you can build a robust and correct solution for the Alien Dictionary problem.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;Leetcode: 269 - Alien Dictionary code in python java and c++&lt;/strong&gt; problem is a quintessential example of how real-world ordering problems can be modeled and solved using graph theory and topological sort. We've explored the core concepts, detailed the step-by-step process of constructing the graph and applying Kahn's algorithm, and provided comprehensive code implementations in Python, Java, and C++.&lt;/p&gt;
&lt;p&gt;Mastering this problem not only enhances your understanding of graph algorithms but also sharpens your ability to translate abstract problem statements into concrete data structures and algorithms. The key takeaways include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Identifying partial orderings to build a directed graph.&lt;/li&gt;
&lt;li&gt;Using Kahn's algorithm (BFS-based topological sort) for efficient ordering.&lt;/li&gt;
&lt;li&gt;Detecting cycles in the graph to determine if a valid order exists.&lt;/li&gt;
&lt;li&gt;Handling critical edge cases like prefix rules and duplicate edges.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With the insights and code provided, you are now well-equipped to tackle similar graph-based challenges. Keep practicing with various graph problems to solidify your understanding and algorithmic intuition. For another challenging graph problem solved with BFS, check out &lt;a href="/leetcode-127-word-ladder-bfs-tutorial/"&gt;Leetcode 127 Word Ladder: Master the BFS Approach Easily&lt;/a&gt;. Happy coding!&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: Why is the Alien Dictionary problem considered a graph problem?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The problem involves deducing an unknown lexicographical order from a list of sorted words. This creates a set of directed dependencies between characters (e.g., 'a' must come before 'b'). These characters can be represented as nodes, and the dependencies as directed edges in a graph, making it a classic graph ordering problem.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is topological sort, and why is it crucial for solving Alien Dictionary?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: Topological sort is an algorithm for ordering the vertices of a directed acyclic graph (DAG) such that for every directed edge from vertex 'u' to vertex 'v', 'u' comes before 'v' in the ordering. It's crucial for Alien Dictionary because it allows us to derive a valid sequence of characters based on the partial orderings extracted from the input words.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: How does the solution detect if a valid alien alphabet order cannot be determined?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: A valid order cannot be determined if there's a cycle in the dependency graph (e.g., 'a' before 'b', 'b' before 'c', and 'c' before 'a'). Kahn's algorithm, used in the solution, detects cycles if the total number of characters successfully added to the sorted result is less than the total number of unique characters in the alphabet. This indicates that some characters were part of a cycle and could never reach an in-degree of zero.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Topological_sorting"&gt;Wikipedia: Topological Sorting&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/topological-sorting-using-kahn-algorithm/"&gt;GeeksforGeeks: Kahn's Algorithm for Topological Sort&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/alien-dictionary/"&gt;LeetCode Problem 269: Alien Dictionary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.cs.princeton.edu/courses/archive/fall13/cos226/lectures/42DirectedGraphs.pdf"&gt;Princeton University: Directed Graphs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="LeetCode"/><category term="Coding Interview"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/leetcode-269-alien-dictionary-code-python-java-cpp-hero.webp" width="1200"/><media:title type="plain">Leetcode: 269 - Alien Dictionary Code in Python, Java, C++</media:title><media:description type="plain">Master Leetcode 269: Alien Dictionary. Learn to implement this challenging graph problem using topological sort with code examples in Python, Java, and C++.</media:description></entry><entry><title>Leetcode 127 Word Ladder: Master the BFS Approach Easily</title><link href="https://analyticsdrive.tech/leetcode-127-word-ladder-bfs-tutorial/" rel="alternate"/><published>2026-02-23T14:04:00+05:30</published><updated>2026-04-21T04:43:51.503452+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-23:/leetcode-127-word-ladder-bfs-tutorial/</id><summary type="html">&lt;p&gt;Dive deep into Leetcode 127 Word Ladder with a comprehensive tutorial. Learn the Breadth-First Search (BFS) approach to solve this challenging problem.&lt;/p&gt;</summary><content type="html">&lt;h2 id="introduction-to-leetcode-127-word-ladder"&gt;Introduction to Leetcode 127 Word Ladder&lt;/h2&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#introduction-to-leetcode-127-word-ladder"&gt;Introduction to Leetcode 127 Word Ladder&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#prerequisites-for-solving-word-ladder"&gt;Prerequisites for Solving Word Ladder&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-the-leetcode-127-word-ladder-problem"&gt;Understanding the Leetcode 127 Word Ladder Problem&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#why-bfs-is-the-ideal-approach"&gt;Why BFS is the Ideal Approach&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conceptualizing-the-graph"&gt;Conceptualizing the Graph&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-by-step-solution-for-leetcode-127-word-ladder"&gt;Step-by-Step Solution for Leetcode 127 Word Ladder&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-1-initialize-data-structures-and-validate-input"&gt;Step 1: Initialize Data Structures and Validate Input&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-2-pre-process-the-word-list-for-efficient-neighbor-lookups"&gt;Step 2: Pre-process the Word List for Efficient Neighbor Lookups&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-3-start-the-breadth-first-search-traversal"&gt;Step 3: Start the Breadth-First Search Traversal&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-4-process-the-queue-until-empty"&gt;Step 4: Process the Queue Until Empty&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-5-handle-no-path-found"&gt;Step 5: Handle No Path Found&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-code-implementation"&gt;Python Code Implementation&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#code-explanation"&gt;Code Explanation:&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#complexity-analysis"&gt;Complexity Analysis&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#time-complexity"&gt;Time Complexity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#space-complexity"&gt;Space Complexity&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#common-mistakes-and-how-to-avoid-them"&gt;Common Mistakes and How to Avoid Them&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#frequently-asked-questions"&gt;Frequently Asked Questions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;p&gt;Welcome to this in-depth tutorial where we'll explore &lt;strong&gt;Leetcode 127 Word Ladder&lt;/strong&gt;, a classic problem that masterfully combines graph theory with string manipulation. This challenge is frequently encountered in technical interviews and is an excellent way to solidify your understanding of Breadth-First Search (BFS). Our goal is to make it easy for you to master the BFS approach, providing clear steps and a robust Python implementation.&lt;/p&gt;
&lt;p&gt;The Word Ladder problem asks us to find the shortest transformation sequence from a &lt;code&gt;beginWord&lt;/code&gt; to an &lt;code&gt;endWord&lt;/code&gt;, given a dictionary &lt;code&gt;wordList&lt;/code&gt;. Each step in the transformation must change only one letter, and every intermediate word must exist in the &lt;code&gt;wordList&lt;/code&gt;. This problem inherently screams "shortest path in an unweighted graph," making BFS the perfect algorithm to tackle it efficiently. By the end of this guide, you'll not only understand the solution but also be able to implement it confidently.&lt;/p&gt;
&lt;h2 id="prerequisites-for-solving-word-ladder"&gt;Prerequisites for Solving Word Ladder&lt;/h2&gt;
&lt;p&gt;Before we dive deep into the solution for Leetcode 127 Word Ladder, it's beneficial to have a solid understanding of a few fundamental concepts. These prerequisites will ensure you can follow along with the logic and code without getting stuck on basics. Familiarity with these topics will significantly enhance your learning experience and your ability to apply the solution effectively.&lt;/p&gt;
&lt;p&gt;First, a good grasp of &lt;strong&gt;Breadth-First Search (BFS)&lt;/strong&gt; is essential. BFS is a graph traversal algorithm that explores all the neighbor nodes at the present depth level before moving on to the nodes at the next depth level. It's particularly suited for finding the shortest path in unweighted graphs, which is precisely what the Word Ladder problem requires. If you're new to BFS, a quick review of its mechanics, queues, and visited sets will be incredibly helpful. For a practical application of BFS in another challenging problem, check out our guide on &lt;a href="/01-matrix-problem-shortest-distance-bfs-dp-explained/"&gt;Unraveling the 01 Matrix: Finding the Nearest Zero with BFS and DP&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Second, an understanding of &lt;strong&gt;Graph Theory Basics&lt;/strong&gt; is crucial. The Word Ladder problem can be modeled as finding a path in an implicit graph where words are nodes and an edge exists between two words if they differ by exactly one letter. Knowing what nodes, edges, and paths represent in this context will make the solution much clearer. Exploring related graph algorithms, such as &lt;a href="/mastering-depth-first-search/"&gt;Mastering Depth-First Search (DFS)&lt;/a&gt;, can further solidify your understanding of graph traversal techniques. Concepts like adjacency are key to visualizing how words connect.&lt;/p&gt;
&lt;p&gt;Lastly, proficiency in &lt;strong&gt;Python Data Structures&lt;/strong&gt; such as lists, sets, and dictionaries (hash maps) will be very beneficial. We'll be using a queue for BFS, a set to keep track of visited words, and a dictionary to efficiently find potential neighbors. A basic understanding of string manipulation in Python will also be helpful for tasks like comparing words or generating generic states.&lt;/p&gt;
&lt;h2 id="understanding-the-leetcode-127-word-ladder-problem"&gt;Understanding the Leetcode 127 Word Ladder Problem&lt;/h2&gt;
&lt;p&gt;The core of successfully solving any algorithmic problem lies in a thorough understanding of its statement, constraints, and examples. For &lt;strong&gt;Leetcode 127 Word Ladder&lt;/strong&gt;, the problem asks us to find the length of the shortest transformation sequence from a &lt;code&gt;beginWord&lt;/code&gt; to an &lt;code&gt;endWord&lt;/code&gt;. This transformation must adhere to specific rules: each adjacent word in the sequence must differ by exactly one letter, and every transformed word (except the &lt;code&gt;beginWord&lt;/code&gt;) must be present in a given &lt;code&gt;wordList&lt;/code&gt;. If no such transformation sequence exists, we should return 0.&lt;/p&gt;
&lt;p&gt;Let's consider an illustrative example to clarify the problem statement. Suppose &lt;code&gt;beginWord = "hit"&lt;/code&gt;, &lt;code&gt;endWord = "cog"&lt;/code&gt;, and &lt;code&gt;wordList = ["hot","dot","dog","lot","log","cog"]&lt;/code&gt;. We need to find the shortest sequence. A possible transformation could be:
&lt;code&gt;hit -&amp;gt; hot -&amp;gt; dot -&amp;gt; dog -&amp;gt; cog&lt;/code&gt;.
In this sequence, "hit" differs from "hot" by one letter, "hot" from "dot" by one, and so on, with all intermediate words (&lt;code&gt;hot&lt;/code&gt;, &lt;code&gt;dot&lt;/code&gt;, &lt;code&gt;dog&lt;/code&gt;, &lt;code&gt;log&lt;/code&gt;, &lt;code&gt;cog&lt;/code&gt;) existing in the &lt;code&gt;wordList&lt;/code&gt;. The length of this sequence is 5. We are looking for the &lt;em&gt;shortest&lt;/em&gt; such sequence.&lt;/p&gt;
&lt;p&gt;Key constraints and considerations for this problem include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;All words have the same length.&lt;/li&gt;
&lt;li&gt;All words consist of lowercase English letters.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;beginWord&lt;/code&gt; and &lt;code&gt;endWord&lt;/code&gt; are non-empty and differ from each other.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;endWord&lt;/code&gt; &lt;em&gt;must&lt;/em&gt; be in &lt;code&gt;wordList&lt;/code&gt;. If it's not, no path exists, and the answer is 0. &lt;code&gt;beginWord&lt;/code&gt; does &lt;em&gt;not&lt;/em&gt; need to be in &lt;code&gt;wordList&lt;/code&gt;, but if it is, it can be part of the intermediate path. However, when we start the BFS, &lt;code&gt;beginWord&lt;/code&gt; acts as our initial node.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;wordList&lt;/code&gt; contains distinct words.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The goal is not to return the sequence itself, but its length. The &lt;code&gt;beginWord&lt;/code&gt; counts as one word in the sequence. Thus, if &lt;code&gt;beginWord = "a"&lt;/code&gt; and &lt;code&gt;endWord = "c"&lt;/code&gt; with &lt;code&gt;wordList = ["a", "b", "c"]&lt;/code&gt;, the sequence &lt;code&gt;a -&amp;gt; b -&amp;gt; c&lt;/code&gt; has a length of 3.&lt;/p&gt;
&lt;h2 id="why-bfs-is-the-ideal-approach"&gt;Why BFS is the Ideal Approach&lt;/h2&gt;
&lt;p&gt;When tackling the Leetcode 127 Word Ladder problem, the choice of algorithm is paramount, and Breadth-First Search (BFS) stands out as the ideal candidate. The primary reason for this is the problem's explicit requirement to find the &lt;em&gt;shortest&lt;/em&gt; transformation sequence. BFS inherently guarantees finding the shortest path in an unweighted graph, which perfectly aligns with this objective.&lt;/p&gt;
&lt;p&gt;Let's break down why BFS is so suitable here. Imagine each word in our &lt;code&gt;wordList&lt;/code&gt; (and the &lt;code&gt;beginWord&lt;/code&gt;) as a node in a graph. An edge exists between two nodes (words) if they differ by exactly one letter. Since each "step" or "transformation" has an equal "cost" (changing one letter), the graph is unweighted. BFS explores the graph layer by layer, expanding outwards from the starting node. This means it will always discover all nodes at depth &lt;code&gt;k&lt;/code&gt; before moving to any nodes at depth &lt;code&gt;k+1&lt;/code&gt;. Consequently, the first time it reaches the &lt;code&gt;endWord&lt;/code&gt;, it guarantees that this path is the shortest possible path from the &lt;code&gt;beginWord&lt;/code&gt; because all shorter paths (if they existed) would have been explored and completed at earlier depths.&lt;/p&gt;
&lt;p&gt;In contrast, Depth-First Search (DFS) would not be suitable for finding the shortest path directly. DFS explores as far as possible along each branch before backtracking. While DFS can find &lt;em&gt;a&lt;/em&gt; path, there's no guarantee it would be the shortest one without additional modifications (like tracking minimum length and exploring all paths, which essentially becomes dynamic programming or backtracking and is less efficient for shortest path in unweighted graphs). For instance, DFS might explore a very long branch before finding the &lt;code&gt;endWord&lt;/code&gt;, whereas BFS would immediately find the &lt;code&gt;endWord&lt;/code&gt; if it's reachable through a short sequence.&lt;/p&gt;
&lt;p&gt;Furthermore, BFS uses a queue structure, which naturally manages the exploration level by level. We can store &lt;code&gt;(word, level)&lt;/code&gt; pairs in the queue, incrementing the &lt;code&gt;level&lt;/code&gt; for each new layer of words we explore. This allows us to easily track the length of the transformation sequence as we traverse the graph. The moment we dequeue the &lt;code&gt;endWord&lt;/code&gt;, we know its associated &lt;code&gt;level&lt;/code&gt; represents the shortest path length.&lt;/p&gt;
&lt;h2 id="conceptualizing-the-graph"&gt;Conceptualizing the Graph&lt;/h2&gt;
&lt;p&gt;To effectively apply BFS to the Leetcode 127 Word Ladder problem, we first need to clearly conceptualize the underlying graph structure. Although the problem doesn't explicitly give us an adjacency list or matrix, we can infer a graph where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Nodes&lt;/strong&gt;: Each word in the &lt;code&gt;wordList&lt;/code&gt; (and the &lt;code&gt;beginWord&lt;/code&gt;) represents a node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Edges&lt;/strong&gt;: An edge exists between two words if they differ by exactly one letter. This means they are "one-step transformable" from each other.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The challenge lies in efficiently finding these edges. A naive approach would be to compare every word in the &lt;code&gt;wordList&lt;/code&gt; with every other word to check for a one-letter difference. This would be an &lt;code&gt;O(N^2 * L)&lt;/code&gt; operation to build the graph upfront, where &lt;code&gt;N&lt;/code&gt; is the number of words and &lt;code&gt;L&lt;/code&gt; is the length of each word. For larger &lt;code&gt;wordList&lt;/code&gt; sizes, this pre-processing can be prohibitively slow.&lt;/p&gt;
&lt;p&gt;A more optimized approach, often referred to as the "wildcard" or "generic state" method, allows us to find neighbors much more efficiently. Instead of comparing word pairs, we pre-process the &lt;code&gt;wordList&lt;/code&gt; to create a map (dictionary) where keys are "generic words" (words with one letter replaced by a wildcard, like &lt;code&gt;*&lt;/code&gt;) and values are lists of actual words that match that generic pattern.&lt;/p&gt;
&lt;p&gt;For example, if we have words like "hot", "dot", "lot", then:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;h*t&lt;/code&gt; would map to &lt;code&gt;["hot"]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;*ot&lt;/code&gt; would map to &lt;code&gt;["hot", "dot", "lot"]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ho*&lt;/code&gt; would map to &lt;code&gt;["hot"]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;d*t&lt;/code&gt; would map to &lt;code&gt;["dot"]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;do*&lt;/code&gt; would map to &lt;code&gt;["dot"]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;l*t&lt;/code&gt; would map to &lt;code&gt;["lot"]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;lo*&lt;/code&gt; would map to &lt;code&gt;["lot"]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When we are processing a &lt;code&gt;current_word&lt;/code&gt; (say, "hot"), we can generate all its &lt;code&gt;L&lt;/code&gt; generic patterns (&lt;code&gt;*ot&lt;/code&gt;, &lt;code&gt;h*t&lt;/code&gt;, &lt;code&gt;ho*&lt;/code&gt;). For each generic pattern, we look it up in our pre-processed map. The list of words associated with that generic pattern will give us all immediate neighbors that differ by one letter. This significantly speeds up neighbor discovery during the BFS, making it close to &lt;code&gt;O(L)&lt;/code&gt; for each word, rather than &lt;code&gt;O(N*L)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This &lt;code&gt;all_combo_dict&lt;/code&gt; (our wildcard dictionary) is critical for performance. It transforms the problem from repeatedly scanning the entire &lt;code&gt;wordList&lt;/code&gt; for neighbors to a simple dictionary lookup. We need to be careful with edge cases; for instance, the &lt;code&gt;beginWord&lt;/code&gt; might not be in the &lt;code&gt;wordList&lt;/code&gt;, but the &lt;code&gt;endWord&lt;/code&gt; must be. If &lt;code&gt;endWord&lt;/code&gt; is not in &lt;code&gt;wordList&lt;/code&gt;, no path is possible, and we can immediately return 0.&lt;/p&gt;
&lt;h2 id="step-by-step-solution-for-leetcode-127-word-ladder"&gt;Step-by-Step Solution for Leetcode 127 Word Ladder&lt;/h2&gt;
&lt;p&gt;Let's walk through the detailed steps to implement the BFS solution for the Leetcode 127 Word Ladder problem. This structured approach will ensure clarity and help you understand the logic behind each part of the code.&lt;/p&gt;
&lt;h3 id="step-1-initialize-data-structures-and-validate-input"&gt;Step 1: Initialize Data Structures and Validate Input&lt;/h3&gt;
&lt;p&gt;The first crucial step is to set up our environment and handle initial conditions. We need to ensure that the &lt;code&gt;endWord&lt;/code&gt; is actually reachable within the given &lt;code&gt;wordList&lt;/code&gt;. If &lt;code&gt;endWord&lt;/code&gt; is not present, no transformation is possible, so we can immediately return 0.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Word List to Set:&lt;/strong&gt; Convert &lt;code&gt;wordList&lt;/code&gt; into a &lt;code&gt;set&lt;/code&gt; for &lt;code&gt;O(1)&lt;/code&gt; average time complexity lookups. This is crucial for performance when checking if a word exists in the dictionary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Queue for BFS:&lt;/strong&gt; Initialize a &lt;code&gt;deque&lt;/code&gt; (double-ended queue) from the &lt;code&gt;collections&lt;/code&gt; module. This will store tuples of &lt;code&gt;(word, level)&lt;/code&gt;, where &lt;code&gt;word&lt;/code&gt; is the current word being processed, and &lt;code&gt;level&lt;/code&gt; is its distance from &lt;code&gt;beginWord&lt;/code&gt;. Our BFS starts with &lt;code&gt;(beginWord, 1)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visited Set:&lt;/strong&gt; Initialize another &lt;code&gt;set&lt;/code&gt; to keep track of words we have already visited. This prevents cycles and redundant processing, ensuring we find the shortest path and don't get stuck in loops. Mark &lt;code&gt;beginWord&lt;/code&gt; as visited from the start.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-2-pre-process-the-word-list-for-efficient-neighbor-lookups"&gt;Step 2: Pre-process the Word List for Efficient Neighbor Lookups&lt;/h3&gt;
&lt;p&gt;This is the optimization step using "generic states" or "wildcard patterns." Instead of repeatedly generating neighbors by comparing words, we build an adjacency map beforehand.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;all_combo_dict&lt;/code&gt;:&lt;/strong&gt; Create a dictionary, let's call it &lt;code&gt;all_combo_dict&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;Iterate through every &lt;code&gt;word&lt;/code&gt; in the &lt;code&gt;word_set&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For each &lt;code&gt;word&lt;/code&gt;, generate all possible "generic words" by replacing each of its letters with a wildcard character (e.g., &lt;code&gt;*&lt;/code&gt;). For a word "hot" of length &lt;code&gt;L=3&lt;/code&gt;, generate &lt;code&gt;*ot&lt;/code&gt;, &lt;code&gt;h*t&lt;/code&gt;, &lt;code&gt;ho*&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Store these generic words as keys in &lt;code&gt;all_combo_dict&lt;/code&gt;. The value for each key should be a list of actual words from &lt;code&gt;word_set&lt;/code&gt; that match this generic pattern.&lt;/li&gt;
&lt;li&gt;Example: If &lt;code&gt;word_set&lt;/code&gt; contains "hot", "dot", "lot", then &lt;code&gt;all_combo_dict['*ot']&lt;/code&gt; would eventually store &lt;code&gt;["hot", "dot", "lot"]&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This pre-processing step creates an efficient lookup mechanism. When we need to find neighbors for a word &lt;code&gt;X&lt;/code&gt;, we just generate &lt;code&gt;L&lt;/code&gt; generic patterns for &lt;code&gt;X&lt;/code&gt;, and for each pattern, retrieve the list of matching words from &lt;code&gt;all_combo_dict&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id="step-3-start-the-breadth-first-search-traversal"&gt;Step 3: Start the Breadth-First Search Traversal&lt;/h3&gt;
&lt;p&gt;With our data structures initialized and our &lt;code&gt;all_combo_dict&lt;/code&gt; ready, we can now begin the core BFS algorithm.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Enqueue Initial State:&lt;/strong&gt; Add the &lt;code&gt;(beginWord, 1)&lt;/code&gt; tuple to our &lt;code&gt;queue&lt;/code&gt;. The &lt;code&gt;1&lt;/code&gt; represents the length of the sequence starting with &lt;code&gt;beginWord&lt;/code&gt; itself.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark as Visited:&lt;/strong&gt; Immediately add &lt;code&gt;beginWord&lt;/code&gt; to our &lt;code&gt;visited&lt;/code&gt; set to prevent re-processing it.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-4-process-the-queue-until-empty"&gt;Step 4: Process the Queue Until Empty&lt;/h3&gt;
&lt;p&gt;This is the main loop of our BFS. We continue as long as there are words in our queue to process.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Dequeue Current Word:&lt;/strong&gt; In each iteration, &lt;code&gt;pop&lt;/code&gt; the leftmost element (FIFO) from the &lt;code&gt;queue&lt;/code&gt;. This element will be a &lt;code&gt;(current_word, level)&lt;/code&gt; tuple.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Check for End Word:&lt;/strong&gt; If &lt;code&gt;current_word&lt;/code&gt; is equal to &lt;code&gt;endWord&lt;/code&gt;, we've found the shortest path! Return &lt;code&gt;level&lt;/code&gt; immediately. Since BFS explores level by level, the first time &lt;code&gt;endWord&lt;/code&gt; is reached, it must be via the shortest possible sequence.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Generate Neighbors:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;For each character position &lt;code&gt;i&lt;/code&gt; from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;L-1&lt;/code&gt; (where &lt;code&gt;L&lt;/code&gt; is the length of &lt;code&gt;current_word&lt;/code&gt;):&lt;ul&gt;
&lt;li&gt;Create a &lt;code&gt;generic_word&lt;/code&gt; by replacing the character at position &lt;code&gt;i&lt;/code&gt; with a wildcard (&lt;code&gt;*&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Look up this &lt;code&gt;generic_word&lt;/code&gt; in &lt;code&gt;all_combo_dict&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For every &lt;code&gt;neighbor_word&lt;/code&gt; in the list retrieved from &lt;code&gt;all_combo_dict&lt;/code&gt; for that &lt;code&gt;generic_word&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Check Visited:&lt;/strong&gt; If &lt;code&gt;neighbor_word&lt;/code&gt; has not been visited (&lt;code&gt;neighbor_word&lt;/code&gt; not in &lt;code&gt;visited&lt;/code&gt;):&lt;ul&gt;
&lt;li&gt;Add &lt;code&gt;neighbor_word&lt;/code&gt; to the &lt;code&gt;visited&lt;/code&gt; set.&lt;/li&gt;
&lt;li&gt;Enqueue &lt;code&gt;(neighbor_word, level + 1)&lt;/code&gt; into the &lt;code&gt;queue&lt;/code&gt;. This indicates we've found a new word one step further in the transformation sequence.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="step-5-handle-no-path-found"&gt;Step 5: Handle No Path Found&lt;/h3&gt;
&lt;p&gt;If the &lt;code&gt;queue&lt;/code&gt; becomes empty, and we have not returned from the loop (meaning &lt;code&gt;endWord&lt;/code&gt; was never found), it signifies that there is no valid transformation sequence from &lt;code&gt;beginWord&lt;/code&gt; to &lt;code&gt;endWord&lt;/code&gt; under the given constraints. In this scenario, we should return 0.&lt;/p&gt;
&lt;p&gt;This step-by-step breakdown covers the entire logic for solving Leetcode 127 Word Ladder using BFS with the wildcard optimization. The next section will present the actual Python code implementation.&lt;/p&gt;
&lt;h2 id="python-code-implementation"&gt;Python Code Implementation&lt;/h2&gt;
&lt;p&gt;Here's the complete Python implementation of the BFS solution for Leetcode 127 Word Ladder, incorporating all the steps discussed.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;collections&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;typing&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;ladderLength&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;beginWord&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;endWord&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wordList&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;List&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Step 1: Validate Input and Initialize Data Structures&lt;/span&gt;
        &lt;span class="c1"&gt;# Convert wordList to a set for O(1) average time complexity lookups.&lt;/span&gt;
        &lt;span class="n"&gt;word_set&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wordList&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# If endWord is not in the wordList, no transformation is possible.&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;endWord&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;word_set&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

        &lt;span class="c1"&gt;# Queue for BFS, storing (word, level) tuples.&lt;/span&gt;
        &lt;span class="c1"&gt;# Start with beginWord at level 1.&lt;/span&gt;
        &lt;span class="n"&gt;queue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;&lt;span class="p"&gt;([(&lt;/span&gt;&lt;span class="n"&gt;beginWord&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)])&lt;/span&gt;

        &lt;span class="c1"&gt;# Visited set to keep track of words already processed.&lt;/span&gt;
        &lt;span class="n"&gt;visited&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;beginWord&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;# Length of words. All words have the same length as per constraints.&lt;/span&gt;
        &lt;span class="n"&gt;L&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;beginWord&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 2: Pre-process the Word List for Efficient Neighbor Lookups&lt;/span&gt;
        &lt;span class="c1"&gt;# all_combo_dict maps generic words (with a wildcard) to a list of actual words.&lt;/span&gt;
        &lt;span class="n"&gt;all_combo_dict&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;word&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;word_set&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="c1"&gt;# Create a generic word by replacing the i-th char with &amp;#39;*&amp;#39;&lt;/span&gt;
                &lt;span class="n"&gt;generic_word&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;[:&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;*&amp;quot;&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:]&lt;/span&gt;
                &lt;span class="c1"&gt;# Add the actual word to the list for this generic pattern&lt;/span&gt;
                &lt;span class="n"&gt;all_combo_dict&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;setdefault&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;generic_word&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[])&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 3 &amp;amp; 4: Start and Process the BFS Traversal&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current_word&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;level&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;popleft&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Dequeue (word, level)&lt;/span&gt;

            &lt;span class="c1"&gt;# If current_word is the endWord, we found the shortest path.&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current_word&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;endWord&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;level&lt;/span&gt;

            &lt;span class="c1"&gt;# Generate all possible generic transformations for the current word&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;L&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="n"&gt;generic_word&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current_word&lt;/span&gt;&lt;span class="p"&gt;[:&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;&amp;quot;*&amp;quot;&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;current_word&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:]&lt;/span&gt;

                &lt;span class="c1"&gt;# Retrieve all actual words matching this generic pattern&lt;/span&gt;
                &lt;span class="c1"&gt;# from our pre-processed dictionary.&lt;/span&gt;
                &lt;span class="c1"&gt;# Use .get() with an empty list as default to handle cases&lt;/span&gt;
                &lt;span class="c1"&gt;# where a generic_word might not have any matches (e.g., if beginWord&lt;/span&gt;
                &lt;span class="c1"&gt;# creates a generic_word not matching any in word_set)&lt;/span&gt;
                &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;neighbor_word&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;all_combo_dict&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;generic_word&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[]):&lt;/span&gt;
                    &lt;span class="c1"&gt;# If the neighbor word has not been visited yet,&lt;/span&gt;
                    &lt;span class="c1"&gt;# mark it as visited and enqueue it.&lt;/span&gt;
                    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;neighbor_word&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                        &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighbor_word&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                        &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;neighbor_word&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;level&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

        &lt;span class="c1"&gt;# Step 5: Handle No Path Found&lt;/span&gt;
        &lt;span class="c1"&gt;# If the queue becomes empty and endWord was never reached, return 0.&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="code-explanation"&gt;Code Explanation:&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;word_set = set(wordList)&lt;/code&gt;&lt;/strong&gt;: Converts the input list into a set. This allows for &lt;code&gt;O(1)&lt;/code&gt; average time complexity for checking word existence, which is critical for efficiency.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;if endWord not in word_set: return 0&lt;/code&gt;&lt;/strong&gt;: An early exit condition. If the target word isn't even in the dictionary, no transformation is possible.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;queue = deque([(beginWord, 1)])&lt;/code&gt;&lt;/strong&gt;: Initializes a &lt;code&gt;deque&lt;/code&gt; (from &lt;code&gt;collections&lt;/code&gt;) as our BFS queue. Each element is a tuple &lt;code&gt;(word, level)&lt;/code&gt;, where &lt;code&gt;level&lt;/code&gt; is the current path length. &lt;code&gt;beginWord&lt;/code&gt; is at level 1.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;visited = {beginWord}&lt;/code&gt;&lt;/strong&gt;: A set to keep track of words we've already processed. This prevents infinite loops and ensures we find the shortest path. &lt;code&gt;beginWord&lt;/code&gt; is immediately marked as visited.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;L = len(beginWord)&lt;/code&gt;&lt;/strong&gt;: Stores the length of the words, which is constant for all words in the problem.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;all_combo_dict = {}&lt;/code&gt;&lt;/strong&gt;: This dictionary is the core of our optimization.&lt;ul&gt;
&lt;li&gt;It's populated by iterating through every &lt;code&gt;word&lt;/code&gt; in &lt;code&gt;word_set&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For each &lt;code&gt;word&lt;/code&gt;, it generates all &lt;code&gt;L&lt;/code&gt; possible "generic words" by replacing each character with an asterisk &lt;code&gt;*&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;These generic words are keys, and their values are lists of actual words that match that pattern. &lt;code&gt;setdefault&lt;/code&gt; is used to gracefully add words to lists.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;while queue:&lt;/code&gt;&lt;/strong&gt;: The main BFS loop. Continues as long as there are words to explore.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;current_word, level = queue.popleft()&lt;/code&gt;&lt;/strong&gt;: Extracts the word and its current level from the front of the queue.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;if current_word == endWord: return level&lt;/code&gt;&lt;/strong&gt;: If we've reached &lt;code&gt;endWord&lt;/code&gt;, this is the shortest path, so we return its &lt;code&gt;level&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;for i in range(L): generic_word = current_word[:i] + "*" + current_word[i+1:]&lt;/code&gt;&lt;/strong&gt;: This loop generates the &lt;code&gt;L&lt;/code&gt; generic patterns for the &lt;code&gt;current_word&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;for neighbor_word in all_combo_dict.get(generic_word, []):&lt;/code&gt;&lt;/strong&gt;: For each generic pattern, it looks up all potential &lt;code&gt;neighbor_word&lt;/code&gt;s from our pre-processed &lt;code&gt;all_combo_dict&lt;/code&gt;. &lt;code&gt;get(key, [])&lt;/code&gt; safely returns an empty list if the key doesn't exist.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;if neighbor_word not in visited:&lt;/code&gt;&lt;/strong&gt;: Checks if the neighbor has been processed. If not:&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;visited.add(neighbor_word)&lt;/code&gt;&lt;/strong&gt;: Marks it as visited.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;queue.append((neighbor_word, level + 1))&lt;/code&gt;&lt;/strong&gt;: Adds it to the queue for future processing, incrementing the &lt;code&gt;level&lt;/code&gt; as it's one step further.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;return 0&lt;/code&gt;&lt;/strong&gt;: If the loop finishes and &lt;code&gt;endWord&lt;/code&gt; was never found, it means no path exists.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This implementation effectively solves the Leetcode 127 Word Ladder problem by leveraging BFS and a clever pre-processing step for efficient neighbor discovery.&lt;/p&gt;
&lt;h2 id="complexity-analysis"&gt;Complexity Analysis&lt;/h2&gt;
&lt;p&gt;Understanding the time and space complexity of an algorithm is crucial for evaluating its efficiency and suitability for various constraints. For the Leetcode 127 Word Ladder problem, our BFS approach with the wildcard optimization significantly improves performance compared to a naive graph construction.&lt;/p&gt;
&lt;p&gt;Let's define the variables:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;N&lt;/code&gt;: The number of words in the &lt;code&gt;wordList&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;L&lt;/code&gt;: The length of each word (all words have the same length).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="time-complexity"&gt;Time Complexity&lt;/h3&gt;
&lt;p&gt;The overall time complexity can be broken down into two main phases: pre-processing and BFS traversal.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Pre-processing (&lt;code&gt;all_combo_dict&lt;/code&gt; construction):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We iterate through each of the &lt;code&gt;N&lt;/code&gt; words in the &lt;code&gt;word_set&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For each word, we generate &lt;code&gt;L&lt;/code&gt; generic patterns (e.g., "hot" -&amp;gt; "&lt;em&gt;ot", "h&lt;/em&gt;t", "ho*"). Generating each generic pattern involves string slicing and concatenation, which takes &lt;code&gt;O(L)&lt;/code&gt; time.&lt;/li&gt;
&lt;li&gt;Storing these into the &lt;code&gt;all_combo_dict&lt;/code&gt; (which is a hash map) takes &lt;code&gt;O(1)&lt;/code&gt; on average per insertion (assuming good hash function distribution).&lt;/li&gt;
&lt;li&gt;Therefore, the total time for pre-processing is &lt;code&gt;N * L * O(L) = O(N * L^2)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;BFS Traversal:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In the worst-case scenario, every word in &lt;code&gt;word_set&lt;/code&gt; (including &lt;code&gt;beginWord&lt;/code&gt; if it's implicitly added to the graph) might be visited once. So, we process up to &lt;code&gt;N&lt;/code&gt; words.&lt;/li&gt;
&lt;li&gt;When we process a &lt;code&gt;current_word&lt;/code&gt; from the queue:&lt;ul&gt;
&lt;li&gt;We generate &lt;code&gt;L&lt;/code&gt; generic patterns for &lt;code&gt;current_word&lt;/code&gt;, each taking &lt;code&gt;O(L)&lt;/code&gt; time. So &lt;code&gt;O(L^2)&lt;/code&gt; to generate all patterns.&lt;/li&gt;
&lt;li&gt;For each generic pattern, we perform a dictionary lookup in &lt;code&gt;all_combo_dict&lt;/code&gt;. On average, this is &lt;code&gt;O(1)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The lookup returns a list of &lt;code&gt;neighbor_word&lt;/code&gt;s. The total work for iterating through these neighbors across all &lt;code&gt;L&lt;/code&gt; patterns is bounded by the total number of words that can be linked to &lt;code&gt;current_word&lt;/code&gt; via one-letter differences.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;More precisely, for each word &lt;code&gt;u&lt;/code&gt; (node) we visit:&lt;ul&gt;
&lt;li&gt;We generate &lt;code&gt;L&lt;/code&gt; generic patterns (&lt;code&gt;O(L)&lt;/code&gt; time for each, totaling &lt;code&gt;O(L^2)&lt;/code&gt; for all patterns generation if done naively for each word from scratch, or &lt;code&gt;O(L)&lt;/code&gt; if string building is optimized).&lt;/li&gt;
&lt;li&gt;For each pattern, we iterate over its neighbors. The sum of the lengths of all neighbor lists retrieved for a &lt;code&gt;current_word&lt;/code&gt; is equivalent to the degree of that word in the implicit graph.&lt;/li&gt;
&lt;li&gt;Since each word is processed once, and each edge in the graph is effectively traversed at most twice (once in each direction), the total cost for iterating through all neighbors across the entire BFS traversal is proportional to the total number of edges &lt;code&gt;E&lt;/code&gt; in our graph.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;The total number of edges &lt;code&gt;E&lt;/code&gt; can be at most &lt;code&gt;N * L&lt;/code&gt;. For each of the &lt;code&gt;N&lt;/code&gt; words, we check &lt;code&gt;L&lt;/code&gt; generic patterns. Each &lt;code&gt;all_combo_dict&lt;/code&gt; lookup takes &lt;code&gt;O(1)&lt;/code&gt; average, and then we iterate through the list of words. The total number of times we append to the queue and update &lt;code&gt;visited&lt;/code&gt; is proportional to &lt;code&gt;V + E&lt;/code&gt;. Here, &lt;code&gt;V = N&lt;/code&gt; (number of words) and &lt;code&gt;E&lt;/code&gt; (number of connections) can be at most &lt;code&gt;N * L&lt;/code&gt; (as each word has &lt;code&gt;L&lt;/code&gt; generic patterns, each potentially connecting to other words).&lt;/li&gt;
&lt;li&gt;Therefore, the BFS traversal part is &lt;code&gt;O(N * L)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Combining pre-processing and BFS, the overall time complexity is &lt;code&gt;O(N * L^2 + N * L) = O(N * L^2)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="space-complexity"&gt;Space Complexity&lt;/h3&gt;
&lt;p&gt;The space complexity is dominated by the storage of the &lt;code&gt;word_set&lt;/code&gt;, &lt;code&gt;queue&lt;/code&gt;, &lt;code&gt;visited&lt;/code&gt; set, and &lt;code&gt;all_combo_dict&lt;/code&gt;.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;word_set&lt;/code&gt;&lt;/strong&gt;: Stores &lt;code&gt;N&lt;/code&gt; words, each of length &lt;code&gt;L&lt;/code&gt;. &lt;code&gt;O(N * L)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;queue&lt;/code&gt;&lt;/strong&gt;: In the worst case, the queue can hold all &lt;code&gt;N&lt;/code&gt; words. &lt;code&gt;O(N * L)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;visited&lt;/code&gt; set&lt;/strong&gt;: Also stores up to &lt;code&gt;N&lt;/code&gt; words. &lt;code&gt;O(N * L)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;all_combo_dict&lt;/code&gt;&lt;/strong&gt;:&lt;ul&gt;
&lt;li&gt;Keys: There are &lt;code&gt;N&lt;/code&gt; words, and each word generates &lt;code&gt;L&lt;/code&gt; generic patterns. So, at most &lt;code&gt;N * L&lt;/code&gt; unique generic patterns (keys). Each key is of length &lt;code&gt;L&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Values: Each value is a list of words. The total number of words stored across all lists is &lt;code&gt;N * L&lt;/code&gt; (each word &lt;code&gt;w&lt;/code&gt; is added to the list of &lt;code&gt;L&lt;/code&gt; generic patterns it matches).&lt;/li&gt;
&lt;li&gt;Thus, the &lt;code&gt;all_combo_dict&lt;/code&gt; can consume &lt;code&gt;O(N * L^2)&lt;/code&gt; space. This is because there can be &lt;code&gt;O(N * L)&lt;/code&gt; generic keys (each of length L), and &lt;code&gt;O(N * L)&lt;/code&gt; entries in total across all value lists (each word is stored &lt;code&gt;L&lt;/code&gt; times in total).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Overall, the space complexity is &lt;code&gt;O(N * L^2)&lt;/code&gt;, primarily due to the &lt;code&gt;all_combo_dict&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In summary, this optimized BFS approach provides a robust solution with acceptable &lt;code&gt;O(N * L^2)&lt;/code&gt; time and space complexity, making it efficient for typical Leetcode constraints.&lt;/p&gt;
&lt;h2 id="common-mistakes-and-how-to-avoid-them"&gt;Common Mistakes and How to Avoid Them&lt;/h2&gt;
&lt;p&gt;Solving Leetcode 127 Word Ladder can be tricky, and several common pitfalls can lead to incorrect or inefficient solutions. Being aware of these mistakes can help you debug your code more effectively and write a robust solution from the outset.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Forgetting to Handle &lt;code&gt;endWord&lt;/code&gt; Not in &lt;code&gt;wordList&lt;/code&gt;&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Proceeding with the BFS without checking if &lt;code&gt;endWord&lt;/code&gt; exists in the &lt;code&gt;wordList&lt;/code&gt;. If &lt;code&gt;endWord&lt;/code&gt; is not available, no path can ever reach it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How to Avoid&lt;/strong&gt;: Always include an early check: &lt;code&gt;if endWord not in word_set: return 0&lt;/code&gt;. This is a quick win and handles a critical edge case.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Not Using a &lt;code&gt;visited&lt;/code&gt; Set&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Failing to keep track of visited words. This will lead to infinite loops if cycles exist in the graph (e.g., &lt;code&gt;hot -&amp;gt; dot -&amp;gt; hot&lt;/code&gt;) or redundant re-processing of words, negating the "shortest path" guarantee of BFS.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How to Avoid&lt;/strong&gt;: Initialize a &lt;code&gt;visited&lt;/code&gt; set and add &lt;code&gt;beginWord&lt;/code&gt; to it. Before adding any &lt;code&gt;neighbor_word&lt;/code&gt; to the queue, always check &lt;code&gt;if neighbor_word not in visited:&lt;/code&gt; and then &lt;code&gt;visited.add(neighbor_word)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Incorrectly Calculating Path Length (Level)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Off-by-one errors in determining the length of the transformation sequence. Some might start &lt;code&gt;beginWord&lt;/code&gt; at level 0, others might count edges instead of nodes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How to Avoid&lt;/strong&gt;: Be consistent. The problem asks for the &lt;em&gt;number of words&lt;/em&gt; in the shortest sequence. If &lt;code&gt;beginWord&lt;/code&gt; is level 1, then a path &lt;code&gt;beginWord -&amp;gt; word2 -&amp;gt; endWord&lt;/code&gt; has length &lt;code&gt;level_of_endWord&lt;/code&gt;. Sticking to &lt;code&gt;(beginWord, 1)&lt;/code&gt; and incrementing &lt;code&gt;level&lt;/code&gt; for each step is the clearest way. The &lt;code&gt;beginWord&lt;/code&gt; itself counts as the first word.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Inefficient Neighbor Generation (Brute-Force Word Comparison)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: In the BFS loop, iterating through the entire &lt;code&gt;wordList&lt;/code&gt; for &lt;em&gt;every&lt;/em&gt; &lt;code&gt;current_word&lt;/code&gt; to find words that differ by one character. This involves &lt;code&gt;O(N)&lt;/code&gt; comparisons, each taking &lt;code&gt;O(L)&lt;/code&gt; time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How to Avoid&lt;/strong&gt;: Implement the "wildcard" or "generic state" pre-processing step using &lt;code&gt;all_combo_dict&lt;/code&gt;. This reduces neighbor discovery from &lt;code&gt;O(N * L)&lt;/code&gt; to &lt;code&gt;O(L)&lt;/code&gt; (plus average lookup time).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Using DFS for Shortest Path&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Attempting to use Depth-First Search (DFS) directly to find the &lt;em&gt;shortest&lt;/em&gt; path in an unweighted graph. DFS does not guarantee the shortest path without significant modifications (like explicit path tracking and comparing all paths), which makes it less suitable than BFS for this specific problem. If you wish to learn more about DFS, consult our detailed guide on &lt;a href="/mastering-depth-first-search/"&gt;Mastering Depth-First Search (DFS)&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How to Avoid&lt;/strong&gt;: Remember that BFS is the canonical algorithm for finding the shortest path in unweighted graphs. Its level-by-level exploration naturally yields the shortest path upon first reaching the target.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Modifying &lt;code&gt;wordList&lt;/code&gt; During Iteration&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mistake&lt;/strong&gt;: Removing words from the &lt;code&gt;wordList&lt;/code&gt; or &lt;code&gt;word_set&lt;/code&gt; while iterating over it (e.g., trying to use &lt;code&gt;wordList.remove(word)&lt;/code&gt; as a way to mark visited). This can lead to &lt;code&gt;RuntimeError: Set changed size during iteration&lt;/code&gt; or unexpected behavior.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How to Avoid&lt;/strong&gt;: Use a separate &lt;code&gt;visited&lt;/code&gt; set to manage visited states. The &lt;code&gt;word_set&lt;/code&gt; should remain immutable during the BFS traversal itself (after initial pre-processing).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;By keeping these common mistakes in mind, you can significantly streamline your problem-solving process for Leetcode 127 Word Ladder and similar graph traversal challenges.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;We've embarked on a comprehensive journey through &lt;strong&gt;Leetcode 127 Word Ladder&lt;/strong&gt;, dissecting its problem statement, understanding the theoretical underpinnings, and implementing a robust, optimized solution. This problem serves as an excellent illustration of how to model real-world scenarios (or interview challenges) as graph problems and apply classic algorithms for efficient solutions.&lt;/p&gt;
&lt;p&gt;The core takeaway is the power of Breadth-First Search (BFS) in finding the shortest path within an unweighted graph. By conceptualizing words as nodes and one-letter differences as edges, BFS systematically explores the graph layer by layer, guaranteeing the discovery of the shortest transformation sequence first. Furthermore, we delved into a crucial optimization: using a pre-processed &lt;code&gt;all_combo_dict&lt;/code&gt; (wildcard dictionary) to drastically speed up neighbor discovery. This technique transforms a potentially &lt;code&gt;O(N*L)&lt;/code&gt; operation for finding neighbors into a much faster average &lt;code&gt;O(L)&lt;/code&gt; lookup, leading to an overall time complexity of &lt;code&gt;O(N * L^2)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We walked through each step, from initializing essential data structures like the queue and visited set, to building the efficient &lt;code&gt;all_combo_dict&lt;/code&gt;, and finally, executing the BFS traversal itself. The detailed Python code implementation provided a practical application of these concepts, ensuring you have a working solution ready for adaptation. We also highlighted common pitfalls, such as overlooking the &lt;code&gt;endWord&lt;/code&gt;'s presence in &lt;code&gt;wordList&lt;/code&gt; or inefficiently generating neighbors, empowering you to avoid these issues in your own problem-solving endeavors.&lt;/p&gt;
&lt;p&gt;Mastering problems like Leetcode 127 Word Ladder enhances not only your algorithmic skills but also your ability to analyze problem constraints, choose appropriate data structures, and optimize for performance. Keep practicing, and you'll find these patterns reappearing in various forms, ready for you to conquer with your newfound expertise.&lt;/p&gt;
&lt;h2 id="frequently-asked-questions"&gt;Frequently Asked Questions&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Q: Why is BFS preferred over DFS for the Word Ladder problem?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: BFS is ideal because it guarantees finding the shortest path in unweighted graphs by exploring layer by layer. DFS, by contrast, explores depth-first and may find a longer path before eventually finding the shortest one, requiring more complex tracking.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: What is the purpose of the &lt;code&gt;all_combo_dict&lt;/code&gt; (wildcard dictionary)?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: The &lt;code&gt;all_combo_dict&lt;/code&gt; is an optimization that pre-processes the &lt;code&gt;wordList&lt;/code&gt;. It maps generic word patterns (e.g., &lt;code&gt;h*t&lt;/code&gt;) to all actual words that match, allowing for &lt;code&gt;O(L)&lt;/code&gt; average time complexity to find neighbors instead of a brute-force &lt;code&gt;O(N*L)&lt;/code&gt; comparison.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Q: Does the &lt;code&gt;beginWord&lt;/code&gt; need to be in the &lt;code&gt;wordList&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A: No, &lt;code&gt;beginWord&lt;/code&gt; does not need to be in the &lt;code&gt;wordList&lt;/code&gt;. However, the &lt;code&gt;endWord&lt;/code&gt; &lt;em&gt;must&lt;/em&gt; be present in &lt;code&gt;wordList&lt;/code&gt; for a valid transformation path to exist, otherwise, the function should return 0.&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Breadth-first_search"&gt;Breadth-First Search - Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/word-ladder/"&gt;Word Ladder - LeetCode Problem 127&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Graph_theory"&gt;Graph Theory - Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.python.org/3/library/collections.html#collections.deque"&gt;Python collections.deque documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="LeetCode"/><category term="Graph Theory"/><category term="Coding Interview"/><category term="Graph Algorithms"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/leetcode-127-word-ladder-bfs-tutorial.webp" width="1200"/><media:title type="plain">Leetcode 127 Word Ladder: Master the BFS Approach Easily</media:title><media:description type="plain">Dive deep into Leetcode 127 Word Ladder with a comprehensive tutorial. Learn the Breadth-First Search (BFS) approach to solve this challenging problem.</media:description></entry><entry><title>Cracking LeetCode 79: Word Search</title><link href="https://analyticsdrive.tech/leetcode-79-word-search-solution/" rel="alternate"/><published>2026-02-17T14:29:00+05:30</published><updated>2026-04-21T04:43:51.530189+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-17:/leetcode-79-word-search-solution/</id><summary type="html">&lt;p&gt;Dive into LeetCode 79, the Word Search problem. Learn to solve this grid-traversal challenge efficiently using a powerful Depth-First Search (DFS) and backtracking approach.&lt;/p&gt;</summary><content type="html">&lt;hr&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#mastering-leetcode-79-the-word-search-challenge"&gt;Mastering LeetCode 79: The Word Search Challenge&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#understanding-the-leetcode-79-problem"&gt;Understanding the LeetCode 79 Problem&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-intuition-exploring-paths-with-dfs"&gt;The Intuition: Exploring Paths with DFS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#algorithm-breakdown-dfs-with-backtracking"&gt;Algorithm Breakdown: DFS with Backtracking&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#dfsrow-col-index-board-word"&gt;dfs(row, col, index, board, word)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-code-implementation"&gt;Python Code Implementation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#tips-for-similar-problems"&gt;Tips for Similar Problems&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="mastering-leetcode-79-the-word-search-challenge"&gt;Mastering LeetCode 79: The Word Search Challenge&lt;/h2&gt;
&lt;p&gt;Have you ever found yourself staring at a grid of letters, trying to spell out a word? That's precisely the essence of &lt;a href="https://leetcode.com/problems/word-search/"&gt;LeetCode Problem 79: Word Search&lt;/a&gt;. It's a classic algorithmic puzzle that tests your ability to navigate a grid, making it an excellent exercise for honing your &lt;a href="https://en.wikipedia.org/wiki/Depth-first_search"&gt;Depth-First Search (DFS)&lt;/a&gt; and &lt;a href="https://en.wikipedia.org/wiki/Backtracking"&gt;backtracking&lt;/a&gt; skills.&lt;/p&gt;
&lt;p&gt;This problem isn't just a technical exercise; it's a fundamental pattern that appears in many real-world scenarios, from game development to pathfinding. Let's break down how to conquer it.&lt;/p&gt;
&lt;h2 id="understanding-the-leetcode-79-problem"&gt;Understanding the LeetCode 79 Problem&lt;/h2&gt;
&lt;p&gt;The challenge asks us to determine if a given &lt;code&gt;word&lt;/code&gt; exists in a 2D &lt;code&gt;board&lt;/code&gt; of characters. The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are those horizontally or vertically neighboring. Crucially, the same letter cell may &lt;strong&gt;not&lt;/strong&gt; be used more than once.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Consider the board:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;[[&amp;#39;A&amp;#39;,&amp;#39;B&amp;#39;,&amp;#39;C&amp;#39;,&amp;#39;E&amp;#39;],
 [&amp;#39;S&amp;#39;,&amp;#39;F&amp;#39;,&amp;#39;C&amp;#39;,&amp;#39;S&amp;#39;],
 [&amp;#39;A&amp;#39;,&amp;#39;D&amp;#39;,&amp;#39;E&amp;#39;,&amp;#39;E&amp;#39;]]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;And the word: &lt;code&gt;"ABCCED"&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The expected output is &lt;code&gt;true&lt;/code&gt; because we can find 'A' at (0,0), 'B' at (0,1), 'C' at (0,2), 'C' at (1,2), 'E' at (2,3), and 'D' at (1,1). Notice how we traversed from (0,2) to (1,2) for the second 'C'.&lt;/p&gt;
&lt;p&gt;Key constraints usually include the board dimensions and the length of the word. Both are typically small enough for exponential-time solutions involving backtracking to pass within limits.&lt;/p&gt;
&lt;h2 id="the-intuition-exploring-paths-with-dfs"&gt;The Intuition: Exploring Paths with DFS&lt;/h2&gt;
&lt;p&gt;How do we begin to search for a word? A brute-force approach might try to list every possible path starting from every cell, which quickly becomes unmanageable. The key insight lies in using a graph traversal algorithm: Depth-First Search (DFS).&lt;/p&gt;
&lt;p&gt;When we find the first letter of our &lt;code&gt;word&lt;/code&gt; on the &lt;code&gt;board&lt;/code&gt;, we can start a "search path" from that cell. From there, we need to explore all four possible directions (up, down, left, right) for the &lt;em&gt;next&lt;/em&gt; letter in our &lt;code&gt;word&lt;/code&gt;. If we find the next letter, we continue the path. If not, or if we hit a dead end, we need to "backtrack" and try a different path. This recursive exploration is the heart of DFS and backtracking.&lt;/p&gt;
&lt;h2 id="algorithm-breakdown-dfs-with-backtracking"&gt;Algorithm Breakdown: DFS with Backtracking&lt;/h2&gt;
&lt;p&gt;Our solution will comprise two main parts:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;An outer loop&lt;/strong&gt; to iterate through every cell in the &lt;code&gt;board&lt;/code&gt;. If a cell's character matches the first letter of our &lt;code&gt;word&lt;/code&gt;, we initiate a DFS search from that point.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A recursive helper function (DFS)&lt;/strong&gt; that attempts to find the rest of the word.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let's detail the DFS helper function:&lt;/p&gt;
&lt;h3 id="dfsrow-col-index-board-word"&gt;&lt;code&gt;dfs(row, col, index, board, word)&lt;/code&gt;&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Base Case 1: Word Found&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;index&lt;/code&gt; equals the length of &lt;code&gt;word&lt;/code&gt;, it means we've successfully found all characters of the word in sequence. Return &lt;code&gt;True&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Base Case 2: Out of Bounds or Mismatch&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;row&lt;/code&gt; or &lt;code&gt;col&lt;/code&gt; are outside the &lt;code&gt;board&lt;/code&gt; boundaries.&lt;/li&gt;
&lt;li&gt;If the character &lt;code&gt;board[row][col]&lt;/code&gt; does not match &lt;code&gt;word[index]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If the cell &lt;code&gt;(row, col)&lt;/code&gt; has already been visited (we'll mark visited cells).&lt;/li&gt;
&lt;li&gt;In any of these cases, this path is invalid. Return &lt;code&gt;False&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Recursive Step:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Mark Current Cell Visited:&lt;/strong&gt; Temporarily change the character at &lt;code&gt;board[row][col]&lt;/code&gt; to a distinct marker (e.g., '#', '*') to prevent reusing it in the current path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Explore Neighbors:&lt;/strong&gt; Recursively call &lt;code&gt;dfs&lt;/code&gt; for all four adjacent cells:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dfs(row + 1, col, index + 1, ...)&lt;/code&gt; (Down)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(row - 1, col, index + 1, ...)&lt;/code&gt; (Up)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(row, col + 1, index + 1, ...)&lt;/code&gt; (Right)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dfs(row, col - 1, index + 1, ...)&lt;/code&gt; (Left)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Check Results:&lt;/strong&gt; If any of these recursive calls return &lt;code&gt;True&lt;/code&gt;, it means a path was found. Propagate &lt;code&gt;True&lt;/code&gt; upwards.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Backtrack (Unmark Cell):&lt;/strong&gt; &lt;em&gt;Crucially&lt;/em&gt;, restore the character &lt;code&gt;board[row][col]&lt;/code&gt; to its original value. This allows other potential paths (started from different initial cells) to use this cell later. If we don't restore it, we might miss valid paths.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Return False:&lt;/strong&gt; If no path from this cell leads to the full word, return &lt;code&gt;False&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The main function &lt;code&gt;exist(board, word)&lt;/code&gt; will iterate &lt;code&gt;(i, j)&lt;/code&gt; through the &lt;code&gt;board&lt;/code&gt;. If &lt;code&gt;board[i][j] == word[0]&lt;/code&gt;, it calls &lt;code&gt;dfs(i, j, 0, board, word)&lt;/code&gt;. If any such call returns &lt;code&gt;True&lt;/code&gt;, the word exists. If all initial calls fail, return &lt;code&gt;False&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="python-code-implementation"&gt;Python Code Implementation&lt;/h2&gt;
&lt;p&gt;Here's how you might implement this in Python:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;exist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;board&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]],&lt;/span&gt; &lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cols&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;board&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;board&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

        &lt;span class="c1"&gt;# Define directions for movement (up, down, left, right)&lt;/span&gt;
        &lt;span class="n"&gt;directions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;

        &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="c1"&gt;# Base Case 1: Word Found&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;

            &lt;span class="c1"&gt;# Base Case 2: Out of Bounds or Mismatch&lt;/span&gt;
            &lt;span class="c1"&gt;# A visited cell will have its character temporarily changed to &amp;#39;#&amp;#39;&lt;/span&gt;
            &lt;span class="c1"&gt;# which won&amp;#39;t match word[k], effectively handling &amp;#39;already visited&amp;#39;.&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;rows&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;cols&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;board&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]):&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;

            &lt;span class="c1"&gt;# Mark current cell as visited by changing its character&lt;/span&gt;
            &lt;span class="c1"&gt;# Store original character to restore later during backtracking&lt;/span&gt;
            &lt;span class="n"&gt;original_char&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;board&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
            &lt;span class="n"&gt;board&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;#&amp;#39;&lt;/span&gt; &lt;span class="c1"&gt;# Use a special character to mark as visited&lt;/span&gt;

            &lt;span class="c1"&gt;# Explore neighbors&lt;/span&gt;
            &lt;span class="n"&gt;found&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;dr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;directions&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;new_r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;new_r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                    &lt;span class="n"&gt;found&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
                    &lt;span class="k"&gt;break&lt;/span&gt; &lt;span class="c1"&gt;# Optimization: If found, no need to check other directions&lt;/span&gt;

            &lt;span class="c1"&gt;# Backtrack: Restore the original character to the cell&lt;/span&gt;
            &lt;span class="n"&gt;board&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;original_char&lt;/span&gt;

            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;found&lt;/span&gt;

        &lt;span class="c1"&gt;# Iterate through each cell to find the starting character of the word&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rows&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cols&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;board&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;word&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h2 id="time-and-space-complexity-analysis"&gt;Time and Space Complexity Analysis&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(M * N * 3^L)&lt;ul&gt;
&lt;li&gt;&lt;code&gt;M&lt;/code&gt; is the number of rows, &lt;code&gt;N&lt;/code&gt; is the number of columns in the &lt;code&gt;board&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;L&lt;/code&gt; is the length of the &lt;code&gt;word&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;In the worst case, we might start a DFS from every cell (&lt;code&gt;M * N&lt;/code&gt; possibilities).&lt;/li&gt;
&lt;li&gt;For each DFS path, we explore up to &lt;code&gt;L&lt;/code&gt; characters. From each character, we have 4 directions. However, since we cannot go back to the cell we just came from, there are effectively 3 choices for the next step after the first one. Hence, &lt;code&gt;3^L&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(L)&lt;ul&gt;
&lt;li&gt;This is primarily due to the recursion stack depth, which can go as deep as the length of the &lt;code&gt;word&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;We are modifying the &lt;code&gt;board&lt;/code&gt; in-place to mark visited cells, so no additional &lt;code&gt;visited&lt;/code&gt; set/array is explicitly used, saving space. If we used an auxiliary &lt;code&gt;visited&lt;/code&gt; matrix, it would be O(M*N).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="tips-for-similar-problems"&gt;Tips for Similar Problems&lt;/h2&gt;
&lt;p&gt;This problem is a fantastic illustration of grid traversal with DFS and backtracking. Keep these principles in mind for similar challenges:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Identify the Search Space:&lt;/strong&gt; Is it a grid, a tree, or a graph?&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Define Base Cases:&lt;/strong&gt; What conditions stop the recursion (success, failure)?&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Define Recursive Step:&lt;/strong&gt; How do you move from the current state to the next?&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Manage State:&lt;/strong&gt; How do you keep track of visited elements or accumulated results? (Here, modifying the board temporarily serves as the &lt;code&gt;visited&lt;/code&gt; tracker).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Backtracking:&lt;/strong&gt; If a path doesn't lead to a solution, &lt;em&gt;always&lt;/em&gt; revert the changes made to the state to allow other paths to explore.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Practicing problems like "Number of Islands," "Surrounded Regions," or "Pacific Atlantic Water Flow" will further solidify your understanding of these techniques.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Solving LeetCode 79: Word Search isn't just about finding characters on a board; it's about mastering a powerful and widely applicable algorithmic pattern. By understanding and implementing DFS with backtracking, you gain a versatile tool for tackling complex search and exploration problems. Keep practicing, and you'll find these grid-based challenges increasingly intuitive!&lt;/p&gt;
&lt;p&gt;Happy coding!&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/word-search/"&gt;LeetCode Problem 79: Word Search&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Depth-first_search"&gt;Depth-First Search (DFS) on Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Backtracking"&gt;Backtracking on Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/"&gt;LeetCode Official Website&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="LeetCode"/><category term="Graph Theory"/><category term="Coding Interview"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/leetcode-79-word-search-solution.webp" width="1200"/><media:title type="plain">Cracking LeetCode 79: Word Search</media:title><media:description type="plain">Dive into LeetCode 79, the Word Search problem. Learn to solve this grid-traversal challenge efficiently using a powerful Depth-First Search (DFS) and backtracking approach.</media:description></entry><entry><title>Mastering Depth-First Search (DFS)</title><link href="https://analyticsdrive.tech/mastering-depth-first-search/" rel="alternate"/><published>2026-02-16T01:33:00+05:30</published><updated>2026-04-21T04:43:51.540243+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-16:/mastering-depth-first-search/</id><summary type="html">&lt;p&gt;Dive deep into Depth-First Search (DFS), a fundamental graph traversal algorithm. Learn its mechanics, implementation, and powerful applications in programming.&lt;/p&gt;</summary><content type="html">&lt;p&gt;Graphs are powerful tools for modeling relationships, from social networks to intricate computer systems. To make sense of these complex structures, we need efficient ways to explore them. Enter Depth-First Search (DFS), a fundamental algorithm that allows us to systematically traverse a graph.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-depth-first-search-dfs"&gt;What is Depth-First Search (DFS)?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#how-dfs-works-the-core-mechanic"&gt;How DFS Works: The Core Mechanic&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#a-walkthrough-example"&gt;A Walkthrough Example&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#implementing-dfs"&gt;Implementing DFS&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-recursive-implementation"&gt;1. Recursive Implementation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-iterative-implementation-using-a-stack"&gt;2. Iterative Implementation (using a Stack)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#characteristics-of-dfs"&gt;Characteristics of DFS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#powerful-applications-of-dfs"&gt;Powerful Applications of DFS&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#1-finding-connected-components"&gt;1. Finding Connected Components&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#2-topological-sorting"&gt;2. Topological Sorting&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#3-cycle-detection"&gt;3. Cycle Detection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#4-pathfinding-maze-solving"&gt;4. Pathfinding (Maze Solving)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#5-strongly-connected-components-tarjans-kosarajus-algorithms"&gt;5. Strongly Connected Components (Tarjan's, Kosaraju's Algorithms)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#6-biconnectivity-and-cut-vertices"&gt;6. Biconnectivity and Cut Vertices&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#dfs-vs-bfs-when-to-use-which"&gt;DFS vs. BFS: When to Use Which?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;p&gt;If you've ever gotten lost in a maze, always choosing to go as far as possible down one path before backtracking, you've intuitively performed a depth-first search! In this post, we'll unravel the mysteries of DFS, understanding how it works, how to implement it, and its vast applications.&lt;/p&gt;
&lt;h2 id="what-is-depth-first-search-dfs"&gt;What is Depth-First Search (DFS)?&lt;/h2&gt;
&lt;p&gt;Depth-First Search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root (or an arbitrary node) and explores as far as possible along each branch before backtracking. It's like exploring a labyrinth: you pick a path and follow it until you hit a dead end, then you retrace your steps to find an alternative route.&lt;/p&gt;
&lt;p&gt;This "go deep first" strategy contrasts with Breadth-First Search (BFS), which explores all immediate neighbors before moving to the next level of nodes. DFS prioritizes depth over breadth.&lt;/p&gt;
&lt;h2 id="how-dfs-works-the-core-mechanic"&gt;How DFS Works: The Core Mechanic&lt;/h2&gt;
&lt;p&gt;The fundamental idea behind DFS is quite simple:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Visit a node:&lt;/strong&gt; Start at an unvisited node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark as visited:&lt;/strong&gt; Keep track of visited nodes to avoid infinite loops in graphs with cycles.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Explore deeply:&lt;/strong&gt; For each unvisited neighbor of the current node, recursively call DFS on that neighbor.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Backtrack:&lt;/strong&gt; If all neighbors have been visited or there are no unvisited neighbors, backtrack to the previous node and explore other branches.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This process continues until all reachable nodes from the starting point have been visited.&lt;/p&gt;
&lt;h3 id="a-walkthrough-example"&gt;A Walkthrough Example&lt;/h3&gt;
&lt;p&gt;Imagine a simple graph with nodes A, B, C, D, E.
Edges: (A, B), (A, C), (B, D), (C, E)&lt;/p&gt;
&lt;p&gt;Starting DFS from A:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Visit A. Mark A as visited.&lt;/li&gt;
&lt;li&gt;Neighbors of A: B, C. Pick B.&lt;/li&gt;
&lt;li&gt;Visit B. Mark B as visited.&lt;/li&gt;
&lt;li&gt;Neighbors of B: D. Pick D.&lt;/li&gt;
&lt;li&gt;Visit D. Mark D as visited.&lt;/li&gt;
&lt;li&gt;Neighbors of D: None. Backtrack to B.&lt;/li&gt;
&lt;li&gt;All neighbors of B (D) visited. Backtrack to A.&lt;/li&gt;
&lt;li&gt;Neighbors of A: C (B already visited). Pick C.&lt;/li&gt;
&lt;li&gt;Visit C. Mark C as visited.&lt;/li&gt;
&lt;li&gt;Neighbors of C: E. Pick E.&lt;/li&gt;
&lt;li&gt;Visit E. Mark E as visited.&lt;/li&gt;
&lt;li&gt;Neighbors of E: None. Backtrack to C.&lt;/li&gt;
&lt;li&gt;All neighbors of C (E) visited. Backtrack to A.&lt;/li&gt;
&lt;li&gt;All neighbors of A (B, C) visited. DFS complete.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The order of traversal could be A -&amp;gt; B -&amp;gt; D -&amp;gt; C -&amp;gt; E. (Note: Order depends on neighbor processing order).&lt;/p&gt;
&lt;h2 id="implementing-dfs"&gt;Implementing DFS&lt;/h2&gt;
&lt;p&gt;DFS can be implemented in two primary ways: recursively or iteratively using a stack. Both achieve the same result.&lt;/p&gt;
&lt;h3 id="1-recursive-implementation"&gt;1. Recursive Implementation&lt;/h3&gt;
&lt;p&gt;The recursive approach is often more intuitive for DFS, directly mirroring the "explore deeply" principle.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;graph&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;visited&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# To keep track of visited nodes&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;dfs_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Process the node&lt;/span&gt;
        &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;neighbor&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
            &lt;span class="n"&gt;dfs_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;Recursive DFS Traversal:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;dfs_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Start DFS from node &amp;#39;A&amp;#39;&lt;/span&gt;
&lt;span class="c1"&gt;# Expected output: A B D C E&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="2-iterative-implementation-using-a-stack"&gt;2. Iterative Implementation (using a Stack)&lt;/h3&gt;
&lt;p&gt;Since recursion uses the call stack, we can manually manage a stack to achieve an iterative DFS.&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="n"&gt;graph&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;B&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;C&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;D&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[],&lt;/span&gt;
    &lt;span class="s1"&gt;&amp;#39;E&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;dfs_iterative&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start_node&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;visited&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start_node&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot;&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;Iterative DFS Traversal:&amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# Get the top node&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;&amp;quot; &amp;quot;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Process the node&lt;/span&gt;
            &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="c1"&gt;# Add neighbors to stack in reverse order to ensure specific traversal order.&lt;/span&gt;
            &lt;span class="c1"&gt;# The last neighbor pushed will be the first one popped and explored.&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;neighbor&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;reversed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;graph&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;]):&lt;/span&gt; 
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;neighbor&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;stack&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;dfs_iterative&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;&amp;#39;A&amp;#39;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Expected output: A C E B D (order might vary slightly based on neighbor pushing)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h2 id="characteristics-of-dfs"&gt;Characteristics of DFS&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Time Complexity&lt;/strong&gt;: For a graph with &lt;code&gt;V&lt;/code&gt; vertices and &lt;code&gt;E&lt;/code&gt; edges, DFS has a time complexity of O(V + E) because it visits each vertex and edge at most once.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Space Complexity&lt;/strong&gt;: O(V) in the worst case (for the recursion stack or explicit stack), as it might need to store all vertices on the current path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Completeness&lt;/strong&gt;: DFS is complete for finite graphs, meaning it will find a path to a goal state if one exists.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Optimality&lt;/strong&gt;: DFS is not optimal in general; it might find a longer path to a target simply because it explores one branch fully before exploring others.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="powerful-applications-of-dfs"&gt;Powerful Applications of DFS&lt;/h2&gt;
&lt;p&gt;DFS is more than just a traversal algorithm; it's a versatile tool used to solve a wide range of problems in computer science.&lt;/p&gt;
&lt;h3 id="1-finding-connected-components"&gt;1. Finding Connected Components&lt;/h3&gt;
&lt;p&gt;In an undirected graph, DFS can easily identify all nodes belonging to the same connected component. If you start DFS from an unvisited node, all nodes reachable from it form a connected component.&lt;/p&gt;
&lt;h3 id="2-topological-sorting"&gt;2. Topological Sorting&lt;/h3&gt;
&lt;p&gt;For Directed Acyclic Graphs (DAGs), DFS can be used to produce a topological sort, which is a linear ordering of vertices such that for every directed edge U -&amp;gt; V, vertex U comes before V in the ordering. This is crucial for task scheduling.&lt;/p&gt;
&lt;h3 id="3-cycle-detection"&gt;3. Cycle Detection&lt;/h3&gt;
&lt;p&gt;DFS can detect cycles in both directed and undirected graphs. In an undirected graph, if DFS encounters a visited node that is not its immediate parent, a cycle exists. In a directed graph, a cycle is detected if DFS encounters a visited node that is currently in the recursion stack (i.e., an ancestor).&lt;/p&gt;
&lt;h3 id="4-pathfinding-maze-solving"&gt;4. Pathfinding (Maze Solving)&lt;/h3&gt;
&lt;p&gt;DFS is a natural fit for solving mazes. By treating the maze as a graph where junctions are nodes and passages are edges, DFS can explore paths until it finds the exit.&lt;/p&gt;
&lt;h3 id="5-strongly-connected-components-tarjans-kosarajus-algorithms"&gt;5. Strongly Connected Components (Tarjan's, Kosaraju's Algorithms)&lt;/h3&gt;
&lt;p&gt;More advanced algorithms like Tarjan's or Kosaraju's for finding strongly connected components in directed graphs rely heavily on DFS.&lt;/p&gt;
&lt;h3 id="6-biconnectivity-and-cut-vertices"&gt;6. Biconnectivity and Cut Vertices&lt;/h3&gt;
&lt;p&gt;DFS can identify articulation points (cut vertices) and bridges in a graph, which are critical for network reliability analysis.&lt;/p&gt;
&lt;h2 id="dfs-vs-bfs-when-to-use-which"&gt;DFS vs. BFS: When to Use Which?&lt;/h2&gt;
&lt;p&gt;While both DFS and BFS are fundamental graph traversal algorithms, their different strategies make them suitable for different scenarios:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;DFS is preferred for:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Cycle detection&lt;/li&gt;
&lt;li&gt;Topological sorting&lt;/li&gt;
&lt;li&gt;Finding connected components&lt;/li&gt;
&lt;li&gt;Pathfinding in unweighted graphs where &lt;em&gt;any&lt;/em&gt; path is sufficient (e.g., maze solving)&lt;/li&gt;
&lt;li&gt;When the graph is very deep and breadth-first search might consume too much memory.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;BFS is preferred for:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Finding the shortest path in an unweighted graph&lt;/li&gt;
&lt;li&gt;Finding the minimum number of moves&lt;/li&gt;
&lt;li&gt;When the graph is very wide and shallow, and you need to find something close to the source.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Depth-First Search is a cornerstone algorithm in computer science, offering a powerful and elegant way to explore graph structures. Its "go deep" approach, whether implemented recursively or iteratively, provides solutions to a myriad of problems, from detecting cycles to orchestrating task dependencies. Understanding DFS not only sharpens your algorithmic thinking but also equips you with a versatile tool for tackling complex data relationships. So, the next time you encounter a graph problem, remember the deep dive power of DFS!&lt;/p&gt;
&lt;h2 id="further-reading-resources"&gt;Further Reading &amp;amp; Resources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Depth-First Search (Wikipedia)&lt;/strong&gt;: &lt;a href="https://en.wikipedia.org/wiki/Depth-first_search"&gt;https://en.wikipedia.org/wiki/Depth-first_search&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graph Theory (Wikipedia)&lt;/strong&gt;: &lt;a href="https://en.wikipedia.org/wiki/Graph_theory"&gt;https://en.wikipedia.org/wiki/Graph_theory&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Breadth-First Search (Wikipedia)&lt;/strong&gt;: &lt;a href="https://en.wikipedia.org/wiki/Breadth-first_search"&gt;https://en.wikipedia.org/wiki/Breadth-first_search&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Topological Sorting (Wikipedia)&lt;/strong&gt;: &lt;a href="https://en.wikipedia.org/wiki/Topological_sorting"&gt;https://en.wikipedia.org/wiki/Topological_sorting&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Strongly Connected Components (Wikipedia)&lt;/strong&gt;: &lt;a href="https://en.wikipedia.org/wiki/Strongly_connected_component"&gt;https://en.wikipedia.org/wiki/Strongly_connected_component&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Graph Theory"/><category term="Graph Algorithms"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/mastering-depth-first-search.webp" width="1200"/><media:title type="plain">Mastering Depth-First Search (DFS)</media:title><media:description type="plain">Dive deep into Depth-First Search (DFS), a fundamental graph traversal algorithm. Learn its mechanics, implementation, and powerful applications in programming.</media:description></entry><entry><title>Unraveling the 01 Matrix: Finding the Nearest Zero with BFS and DP</title><link href="https://analyticsdrive.tech/01-matrix-problem-shortest-distance-bfs-dp-explained/" rel="alternate"/><published>2026-02-13T15:40:00+05:30</published><updated>2026-04-21T04:43:51.243853+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-13:/01-matrix-problem-shortest-distance-bfs-dp-explained/</id><summary type="html">&lt;p&gt;Master LeetCode's 01 Matrix problem (542) by finding the shortest distance to the nearest zero. Explore efficient solutions using Multi-Source BFS and Dynamic Programming.&lt;/p&gt;</summary><content type="html">&lt;p&gt;The "01 Matrix" problem (LeetCode 542) is a fundamental challenge that effectively tests your graph traversal and dynamic programming skills. Beyond a typical academic exercise, mastering such problems provides a robust foundation for tackling complex shortest path scenarios in real-world applications, spanning from image processing to logistics. In this post, we will dissect this intriguing problem, explore elegant solutions, and equip you with the knowledge to approach similar challenges confidently.&lt;/p&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#what-is-the-01-matrix-problem"&gt;What is the 01 Matrix Problem?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#approach-1-multi-source-breadth-first-search-bfs"&gt;Approach 1: Multi-Source Breadth-First Search (BFS)&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#the-core-idea"&gt;The Core Idea&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#step-by-step-breakdown"&gt;Step-by-Step Breakdown&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-code-example-multi-source-bfs"&gt;Python Code Example (Multi-Source BFS)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#complexity-analysis-bfs"&gt;Complexity Analysis (BFS)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#approach-2-dynamic-programming-dp"&gt;Approach 2: Dynamic Programming (DP)&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-by-step-breakdown_1"&gt;Step-by-Step Breakdown&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-code-example-dynamic-programming"&gt;Python Code Example (Dynamic Programming)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#complexity-analysis-dp"&gt;Complexity Analysis (DP)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#bfs-vs-dp-which-one-to-choose"&gt;BFS vs. DP: Which One to Choose?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id="what-is-the-01-matrix-problem"&gt;What is the 01 Matrix Problem?&lt;/h2&gt;
&lt;p&gt;The "01 Matrix" problem presents a binary matrix, meaning a grid filled with only &lt;code&gt;0&lt;/code&gt;s and &lt;code&gt;1&lt;/code&gt;s. Your task is to transform this matrix into one where each cell indicates the distance to its nearest &lt;code&gt;0&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key Definition:&lt;/strong&gt; The "distance" between two adjacent cells (horizontally or vertically) is 1. We seek the shortest distance, often referred to as the Manhattan distance in a grid context.&lt;/p&gt;
&lt;p&gt;Let's illustrate with an example:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Input Matrix:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;[[0, 0, 0],
 [0, 1, 0],
 [0, 0, 0]]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Expected Output Matrix:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;[[0, 0, 0],
 [0, 1, 0],
 [0, 0, 0]]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Here, the &lt;code&gt;1&lt;/code&gt; at &lt;code&gt;(1,1)&lt;/code&gt; has a &lt;code&gt;0&lt;/code&gt; directly above, below, left, and right, so its shortest distance to a &lt;code&gt;0&lt;/code&gt; is 1. All &lt;code&gt;0&lt;/code&gt;s remain &lt;code&gt;0&lt;/code&gt; as their distance to themselves is 0.&lt;/p&gt;
&lt;p&gt;Another example:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Input Matrix:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;[[0, 1, 1],
 [1, 1, 1],
 [1, 1, 1]]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Expected Output Matrix:&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;[[0, 1, 2],
 [1, 2, 3],
 [2, 3, 4]]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Observe how distances increment as you move further away from the initial &lt;code&gt;0&lt;/code&gt;. This problem is essentially a shortest path problem on an unweighted graph where cells are nodes and adjacent cells are edges.&lt;/p&gt;
&lt;h2 id="approach-1-multi-source-breadth-first-search-bfs"&gt;Approach 1: Multi-Source Breadth-First Search (BFS)&lt;/h2&gt;
&lt;p&gt;BFS is a natural fit for finding the shortest path in an unweighted graph. A key insight here is the presence of &lt;em&gt;multiple&lt;/em&gt; sources (all the &lt;code&gt;0&lt;/code&gt;s) from which distances propagate.&lt;/p&gt;
&lt;h3 id="the-core-idea"&gt;The Core Idea&lt;/h3&gt;
&lt;p&gt;Instead of starting BFS from a single source, we initialize our queue with &lt;em&gt;all&lt;/em&gt; the cells that contain a &lt;code&gt;0&lt;/code&gt;. These cells already have a distance of 0. Then, we expand outwards layer by layer, propagating outwards in a layered fashion. Each time we move to an unvisited neighbor, we know its distance is one more than the current cell's distance.&lt;/p&gt;
&lt;h3 id="step-by-step-breakdown"&gt;Step-by-Step Breakdown&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialize &lt;code&gt;dist&lt;/code&gt; Matrix:&lt;/strong&gt; Create a result matrix &lt;code&gt;dist&lt;/code&gt; of the same dimensions as the input matrix.&lt;ul&gt;
&lt;li&gt;For cells with &lt;code&gt;0&lt;/code&gt; in the input, set &lt;code&gt;dist[r][c] = 0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For cells with &lt;code&gt;1&lt;/code&gt; in the input, set &lt;code&gt;dist[r][c] = -1&lt;/code&gt; (or &lt;code&gt;infinity&lt;/code&gt;) to mark them as unvisited and to be calculated.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Initialize Queue:&lt;/strong&gt; Create a queue and add all &lt;code&gt;(r, c)&lt;/code&gt; coordinates where &lt;code&gt;matrix[r][c] == 0&lt;/code&gt;. These are our starting points.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;BFS Traversal:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;While the queue is not empty:&lt;ul&gt;
&lt;li&gt;Dequeue a cell &lt;code&gt;(r, c)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For each of its four neighbors &lt;code&gt;(nr, nc)&lt;/code&gt; (up, down, left, right):&lt;ul&gt;
&lt;li&gt;Check if &lt;code&gt;(nr, nc)&lt;/code&gt; is within bounds.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;dist[nr][nc]&lt;/code&gt; is &lt;code&gt;-1&lt;/code&gt; (indicating it's an unvisited &lt;code&gt;1&lt;/code&gt;):&lt;ul&gt;
&lt;li&gt;Set &lt;code&gt;dist[nr][nc] = dist[r][c] + 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Enqueue &lt;code&gt;(nr, nc)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Return &lt;code&gt;dist&lt;/code&gt;:&lt;/strong&gt; The &lt;code&gt;dist&lt;/code&gt; matrix now contains the shortest distances.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="python-code-example-multi-source-bfs"&gt;Python Code Example (Multi-Source BFS)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="nn"&gt;collections&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;updateMatrixBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="n"&gt;dist&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
    &lt;span class="n"&gt;q&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

    &lt;span class="c1"&gt;# Initialize dist matrix and queue with all 0s&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
                &lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

    &lt;span class="c1"&gt;# Directions for neighbors (up, down, left, right)&lt;/span&gt;
    &lt;span class="n"&gt;directions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;popleft&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;dr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;directions&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;nr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;nc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt;

            &lt;span class="c1"&gt;# Check bounds and if neighbor is unvisited (value is -1)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;nr&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;nc&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nr&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;nc&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nr&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;nc&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                &lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;nr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;nc&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dist&lt;/span&gt;

&lt;span class="c1"&gt;# Example usage:&lt;/span&gt;
&lt;span class="n"&gt;matrix1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;updateMatrixBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix1&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;# Expected: [[0, 1, 2], [1, 2, 3], [2, 3, 4]]&lt;/span&gt;

&lt;span class="n"&gt;matrix2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;],[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;],[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;updateMatrixBFS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix2&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;# Expected: [[0, 0, 0], [0, 1, 0], [0, 0, 0]]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="complexity-analysis-bfs"&gt;Complexity Analysis (BFS)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(M * N), where M is the number of rows and N is the number of columns. Each cell is added to the queue and processed at most once.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(M * N) for the &lt;code&gt;dist&lt;/code&gt; matrix and, in the worst case, the queue can hold all cells (e.g., a matrix of all &lt;code&gt;0&lt;/code&gt;s or all &lt;code&gt;1&lt;/code&gt;s).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="approach-2-dynamic-programming-dp"&gt;Approach 2: Dynamic Programming (DP)&lt;/h2&gt;
&lt;p&gt;While BFS is intuitive for shortest paths, dynamic programming offers an alternative perspective, especially useful in grid problems where dependencies are directional. The core principle is that a cell's distance to the nearest &lt;code&gt;0&lt;/code&gt; depends on its neighbors' distances.&lt;/p&gt;
&lt;p&gt;The challenge is that you cannot access all neighbors simultaneously if you are building up the solution. We solve this by doing &lt;em&gt;two passes&lt;/em&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;First Pass (Top-Left to Bottom-Right):&lt;/strong&gt; For each cell, we consider its distance from &lt;code&gt;0&lt;/code&gt;s that are &lt;em&gt;above&lt;/em&gt; or to its &lt;em&gt;left&lt;/em&gt;.
    &lt;code&gt;dp[r][c] = min(dp[r][c], dp[r-1][c] + 1, dp[r][c-1] + 1)&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Second Pass (Bottom-Right to Top-Left):&lt;/strong&gt; For each cell, we then refine its distance by considering &lt;code&gt;0&lt;/code&gt;s that are &lt;em&gt;below&lt;/em&gt; or to its &lt;em&gt;right&lt;/em&gt;.
    &lt;code&gt;dp[r][c] = min(dp[r][c], dp[r+1][c] + 1, dp[r][c+1] + 1)&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="step-by-step-breakdown_1"&gt;Step-by-Step Breakdown&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Initialize &lt;code&gt;dp&lt;/code&gt; Matrix:&lt;/strong&gt; Create a &lt;code&gt;dp&lt;/code&gt; matrix of the same dimensions.&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;matrix[r][c] == 0&lt;/code&gt;, set &lt;code&gt;dp[r][c] = 0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;matrix[r][c] == 1&lt;/code&gt;, set &lt;code&gt;dp[r][c]&lt;/code&gt; to a sufficiently large value (effectively infinity) to represent an unknown, maximum distance.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;First Pass (Top-Left to Bottom-Right):&lt;/strong&gt; Iterate &lt;code&gt;r&lt;/code&gt; from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;m-1&lt;/code&gt;, &lt;code&gt;c&lt;/code&gt; from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;For &lt;code&gt;dp[r][c]&lt;/code&gt;, if it's not already 0:&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;r &amp;gt; 0&lt;/code&gt;, &lt;code&gt;dp[r][c] = min(dp[r][c], dp[r-1][c] + 1)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;c &amp;gt; 0&lt;/code&gt;, &lt;code&gt;dp[r][c] = min(dp[r][c], dp[r][c-1] + 1)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Second Pass (Bottom-Right to Top-Left):&lt;/strong&gt; Iterate &lt;code&gt;r&lt;/code&gt; from &lt;code&gt;m-1&lt;/code&gt; down to &lt;code&gt;0&lt;/code&gt;, &lt;code&gt;c&lt;/code&gt; from &lt;code&gt;n-1&lt;/code&gt; down to &lt;code&gt;0&lt;/code&gt;.&lt;ul&gt;
&lt;li&gt;For &lt;code&gt;dp[r][c]&lt;/code&gt;, if it's not already 0:&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;r &amp;lt; m-1&lt;/code&gt;, &lt;code&gt;dp[r][c] = min(dp[r][c], dp[r+1][c] + 1)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;c &amp;lt; n-1&lt;/code&gt;, &lt;code&gt;dp[r][c] = min(dp[r][c], dp[r][c+1] + 1)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Return &lt;code&gt;dp&lt;/code&gt;:&lt;/strong&gt; The &lt;code&gt;dp&lt;/code&gt; matrix now holds the shortest distances.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="python-code-example-dynamic-programming"&gt;Python Code Example (Dynamic Programming)&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;updateMatrixDP&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

    &lt;span class="c1"&gt;# Initialize dp matrix with a large value for 1s, 0 for 0s&lt;/span&gt;
    &lt;span class="c1"&gt;# Using m*n as max possible distance (can be optimized to m+n)&lt;/span&gt;
    &lt;span class="n"&gt;max_dist&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; 
    &lt;span class="n"&gt;dp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="n"&gt;max_dist&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
            &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="c1"&gt;# Check top neighbor&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="c1"&gt;# Check left neighbor&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Second pass: bottom-right to top-left&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="c1"&gt;# Check bottom neighbor&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="c1"&gt;# Check right neighbor&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;dp&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dp&lt;/span&gt;

&lt;span class="c1"&gt;# Example usage:&lt;/span&gt;
&lt;span class="n"&gt;matrix1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;updateMatrixDP&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix1&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;# Expected: [[0, 1, 2], [1, 2, 3], [2, 3, 4]]&lt;/span&gt;

&lt;span class="n"&gt;matrix2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;],[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;],[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt;
&lt;span class="nb"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;updateMatrixDP&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix2&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;# Expected: [[0, 0, 0], [0, 1, 0], [0, 0, 0]]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h3 id="complexity-analysis-dp"&gt;Complexity Analysis (DP)&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(M * N). We iterate through the matrix twice.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(M * N) for the &lt;code&gt;dp&lt;/code&gt; matrix.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="bfs-vs-dp-which-one-to-choose"&gt;BFS vs. DP: Which One to Choose?&lt;/h2&gt;
&lt;p&gt;Both BFS and DP provide correct and efficient solutions with the same time and space complexity for this particular problem.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;BFS:&lt;/strong&gt; Often more intuitive for shortest path problems on unweighted graphs. It guarantees finding the shortest path first because it expands layer by layer. The multi-source aspect is handled elegantly.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DP:&lt;/strong&gt; Requires a bit more thought with the two-pass approach to ensure all dependencies (from all four directions) are covered. However, DP can sometimes be more flexible or adaptable for problems with slightly different constraints or for calculating values beyond just "shortest path."&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For the 01 Matrix problem, the Multi-Source BFS is generally considered the more straightforward and natural approach. However, understanding the DP solution broadens your algorithmic toolkit.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The "01 Matrix" problem (LeetCode 542) is an excellent exercise to solidify your understanding of graph traversal algorithms like Breadth-First Search and dynamic programming. Whether you prefer the elegant ripple effect of a multi-source BFS or the methodical two-pass calculation of DP, both methods lead you to the correct shortest distances to the nearest &lt;code&gt;0&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;By mastering problems like this, you are not just solving a LeetCode puzzle; you are building a strong foundation in algorithmic thinking that is invaluable for any coding challenge or real-world system design task. Continue to practice, explore, and enhance your algorithmic proficiency.&lt;/p&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="Graph Theory"/><category term="Dynamic Programming"/><category term="LeetCode"/><category term="Graph Algorithms"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/01-matrix-problem-shortest-distance-bfs-dp-explained.webp" width="1200"/><media:title type="plain">Unraveling the 01 Matrix: Finding the Nearest Zero with BFS and DP</media:title><media:description type="plain">Master LeetCode's 01 Matrix problem (542) by finding the shortest distance to the nearest zero. Explore efficient solutions using Multi-Source BFS and Dynamic Programming.</media:description></entry><entry><title>Conquering LeetCode 417: A Deep Dive into Pacific Atlantic Water Flow with DFS</title><link href="https://analyticsdrive.tech/leetcode-417-pacific-atlantic-water-flow-dfs-solution/" rel="alternate"/><published>2026-02-13T11:13:00+05:30</published><updated>2026-04-21T04:43:51.524902+05:30</updated><author><name>David Lin</name></author><id>tag:analyticsdrive.tech,2026-02-13:/leetcode-417-pacific-atlantic-water-flow-dfs-solution/</id><summary type="html">&lt;p&gt;Dive into LeetCode 417 (Pacific Atlantic Water Flow). Learn an efficient DFS/BFS approach to solve this classic graph traversal problem and ace your coding interviews!&lt;/p&gt;</summary><content type="html">&lt;h2 id="navigating-the-continental-divide-understanding-leetcode-417"&gt;Navigating the Continental Divide: Understanding LeetCode 417&lt;/h2&gt;
&lt;div class="toc"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#navigating-the-continental-divide-understanding-leetcode-417"&gt;Navigating the Continental Divide: Understanding LeetCode 417&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#unpacking-the-problem-statement"&gt;Unpacking the Problem Statement&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#why-this-problem-is-tricky"&gt;Why This Problem is Tricky&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#the-eureka-moment-flowing-upstream"&gt;The Eureka Moment: Flowing Upstream&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#algorithm-breakdown-dfs-to-the-rescue"&gt;Algorithm Breakdown: DFS to the Rescue&lt;/a&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#step-by-step-implementation"&gt;Step-by-Step Implementation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#python-code-implementation"&gt;Python Code Implementation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="#complexity-analysis"&gt;Complexity Analysis&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#why-this-approach-shines"&gt;Why This Approach Shines&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#conclusion"&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;p&gt;Welcome, fellow coding adventurers! Today, we're setting our compass for a fascinating journey into LeetCode problem 417: "Pacific Atlantic Water Flow." This problem is a brilliant test of your graph traversal skills, specifically your mastery of Depth-First Search (DFS) or Breadth-First Search (BFS). It's a common pattern in technical interviews, making it a crucial concept to grasp.&lt;/p&gt;
&lt;p&gt;Imagine a continent represented by a grid of varying heights. On one side, the mighty Pacific Ocean laps at its shores. On the other, the vast Atlantic Ocean stretches out. Our challenge? To find all the cells on this continent from which water can flow to &lt;em&gt;both&lt;/em&gt; oceans.&lt;/p&gt;
&lt;p&gt;Let's dive in and explore the terrain!&lt;/p&gt;
&lt;h2 id="unpacking-the-problem-statement"&gt;Unpacking the Problem Statement&lt;/h2&gt;
&lt;p&gt;We are given an &lt;code&gt;m x n&lt;/code&gt; integer matrix, &lt;code&gt;heights&lt;/code&gt;, where &lt;code&gt;heights[r][c]&lt;/code&gt; represents the height of the cell at coordinate &lt;code&gt;(r, c)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Here's how the oceans are defined:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Pacific Ocean:&lt;/strong&gt; Touches the top (&lt;code&gt;r=0&lt;/code&gt;) and left (&lt;code&gt;c=0&lt;/code&gt;) edges of the matrix.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Atlantic Ocean:&lt;/strong&gt; Touches the bottom (&lt;code&gt;r=m-1&lt;/code&gt;) and right (&lt;code&gt;c=n-1&lt;/code&gt;) edges of the matrix.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Water can flow from a cell to an adjacent cell (up, down, left, right) if the adjacent cell's height is less than or equal to the current cell's height. Think of it like a topographic map – water always flows downhill or stays level.&lt;/p&gt;
&lt;p&gt;Our ultimate goal is to return a list of &lt;code&gt;[r, c]&lt;/code&gt; coordinates for all cells from which water can reach &lt;em&gt;both&lt;/em&gt; the Pacific and Atlantic oceans.&lt;/p&gt;
&lt;h3 id="why-this-problem-is-tricky"&gt;Why This Problem is Tricky&lt;/h3&gt;
&lt;p&gt;A common initial thought might be to iterate through every cell, perform a DFS/BFS from that cell, and check if it can reach both oceans. While conceptually sound, this approach would be highly inefficient. If the grid is &lt;code&gt;m x n&lt;/code&gt;, and each DFS/BFS takes &lt;code&gt;O(m*n)&lt;/code&gt; time, the total complexity would be &lt;code&gt;O((m*n)^2)&lt;/code&gt;, which is too slow for larger grids. We need a smarter strategy!&lt;/p&gt;
&lt;h2 id="the-eureka-moment-flowing-upstream"&gt;The Eureka Moment: Flowing Upstream&lt;/h2&gt;
&lt;p&gt;The key insight to efficiently solve this problem lies in &lt;strong&gt;reversing the perspective of water flow&lt;/strong&gt;. Instead of trying to determine where water &lt;em&gt;can flow to&lt;/em&gt; from a source cell, let's determine which cells &lt;em&gt;can be reached from&lt;/em&gt; the oceans.&lt;/p&gt;
&lt;p&gt;Think about it: if water can flow from cell &lt;code&gt;A&lt;/code&gt; to cell &lt;code&gt;B&lt;/code&gt; (meaning &lt;code&gt;height[A] &amp;gt;= height[B]&lt;/code&gt;), then conversely, we can say that cell &lt;code&gt;A&lt;/code&gt; is "reachable" from cell &lt;code&gt;B&lt;/code&gt; if we imagine water flowing &lt;em&gt;uphill&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;This leads us to our core strategy:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Identify all cells reachable by the Pacific Ocean:&lt;/strong&gt; Start a traversal (DFS or BFS) from all cells bordering the Pacific Ocean. During this traversal, mark all cells from which water &lt;em&gt;could have originated&lt;/em&gt; and flowed into the Pacific.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Identify all cells reachable by the Atlantic Ocean:&lt;/strong&gt; Do the same for the Atlantic Ocean, starting from its borders and marking all cells that could flow into the Atlantic.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Find the Intersection:&lt;/strong&gt; The cells that are marked as reachable by &lt;em&gt;both&lt;/em&gt; the Pacific and Atlantic oceans are our answer!&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="algorithm-breakdown-dfs-to-the-rescue"&gt;Algorithm Breakdown: DFS to the Rescue&lt;/h2&gt;
&lt;p&gt;We'll use Depth-First Search (DFS) for this traversal, but BFS would work equally well.&lt;/p&gt;
&lt;h3 id="step-by-step-implementation"&gt;Step-by-Step Implementation&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Get the dimensions &lt;code&gt;m&lt;/code&gt; (rows) and &lt;code&gt;n&lt;/code&gt; (columns) of the &lt;code&gt;heights&lt;/code&gt; matrix.&lt;/li&gt;
&lt;li&gt;Create two boolean matrices, &lt;code&gt;can_reach_pacific&lt;/code&gt; and &lt;code&gt;can_reach_atlantic&lt;/code&gt;, both of size &lt;code&gt;m x n&lt;/code&gt;, initialized to &lt;code&gt;False&lt;/code&gt;. These will store whether a cell can reach each respective ocean.&lt;/li&gt;
&lt;li&gt;Define &lt;code&gt;directions&lt;/code&gt; for DFS: &lt;code&gt;[(0, 1), (0, -1), (1, 0), (-1, 0)]&lt;/code&gt; (right, left, down, up).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;DFS Function:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dfs(r, c, visited_matrix, prev_height)&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Base Cases:&lt;/strong&gt;&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;(r, c)&lt;/code&gt; is out of bounds, return.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;(r, c)&lt;/code&gt; has already been visited (marked &lt;code&gt;True&lt;/code&gt; in &lt;code&gt;visited_matrix&lt;/code&gt;), return.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;heights[r][c]&lt;/code&gt; is less than &lt;code&gt;prev_height&lt;/code&gt;, return (water cannot flow uphill from a lower height, which is the reverse logic).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark Current Cell:&lt;/strong&gt; Set &lt;code&gt;visited_matrix[r][c] = True&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recurse:&lt;/strong&gt; For each &lt;code&gt;(dr, dc)&lt;/code&gt; in &lt;code&gt;directions&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;Calculate &lt;code&gt;new_r = r + dr&lt;/code&gt;, &lt;code&gt;new_c = c + dc&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;dfs(new_r, new_c, visited_matrix, heights[r][c])&lt;/code&gt;. Note: &lt;code&gt;heights[r][c]&lt;/code&gt; becomes the &lt;code&gt;prev_height&lt;/code&gt; for the next call, ensuring the "flow upstream" condition (&lt;code&gt;current_height &amp;gt;= next_cell_height&lt;/code&gt;) is maintained.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Populate &lt;code&gt;can_reach_pacific&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Iterate through the first row (&lt;code&gt;r=0&lt;/code&gt;) and the first column (&lt;code&gt;c=0&lt;/code&gt;). These are the direct borders of the Pacific.&lt;/li&gt;
&lt;li&gt;For each cell &lt;code&gt;(0, c)&lt;/code&gt; and &lt;code&gt;(r, 0)&lt;/code&gt;: call &lt;code&gt;dfs(r, c, can_reach_pacific, -1)&lt;/code&gt;. We use &lt;code&gt;-1&lt;/code&gt; as &lt;code&gt;prev_height&lt;/code&gt; to ensure water can always flow "into" the ocean from any bordering cell.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Populate &lt;code&gt;can_reach_atlantic&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Iterate through the last row (&lt;code&gt;r=m-1&lt;/code&gt;) and the last column (&lt;code&gt;c=n-1&lt;/code&gt;). These are the direct borders of the Atlantic.&lt;/li&gt;
&lt;li&gt;For each cell &lt;code&gt;(m-1, c)&lt;/code&gt; and &lt;code&gt;(r, n-1)&lt;/code&gt;: call &lt;code&gt;dfs(r, c, can_reach_atlantic, -1)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Collect Results:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Initialize an empty list &lt;code&gt;result&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Iterate through the entire &lt;code&gt;heights&lt;/code&gt; matrix from &lt;code&gt;r=0&lt;/code&gt; to &lt;code&gt;m-1&lt;/code&gt; and &lt;code&gt;c=0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;can_reach_pacific[r][c]&lt;/code&gt; is &lt;code&gt;True&lt;/code&gt; AND &lt;code&gt;can_reach_atlantic[r][c]&lt;/code&gt; is &lt;code&gt;True&lt;/code&gt;, add &lt;code&gt;[r, c]&lt;/code&gt; to the &lt;code&gt;result&lt;/code&gt; list.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Return &lt;code&gt;result&lt;/code&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id="python-code-implementation"&gt;Python Code Implementation&lt;/h3&gt;
&lt;div class="highlight"&gt;&lt;pre&gt;&lt;span&gt;&lt;/span&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;pacificAtlantic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]])&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]]:&lt;/span&gt;
        &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

        &lt;span class="c1"&gt;# Two boolean matrices to track reachability from Pacific and Atlantic&lt;/span&gt;
        &lt;span class="n"&gt;can_reach_pacific&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
        &lt;span class="n"&gt;can_reach_atlantic&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[[&lt;/span&gt;&lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;

        &lt;span class="c1"&gt;# Directions for DFS: right, left, down, up&lt;/span&gt;
        &lt;span class="n"&gt;directions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;

        &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;visited_matrix&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;prev_height&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="c1"&gt;# Base cases for DFS:&lt;/span&gt;
            &lt;span class="c1"&gt;# 1. Out of bounds&lt;/span&gt;
            &lt;span class="c1"&gt;# 2. Already visited&lt;/span&gt;
            &lt;span class="c1"&gt;# 3. Current cell height is less than previous cell&amp;#39;s height (water can&amp;#39;t flow &amp;quot;upstream&amp;quot; if current is lower)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;visited_matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;prev_height&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt;

            &lt;span class="c1"&gt;# Mark current cell as reachable&lt;/span&gt;
            &lt;span class="n"&gt;visited_matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;

            &lt;span class="c1"&gt;# Explore neighbors&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;dr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;directions&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;new_r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt;
                &lt;span class="c1"&gt;# The &amp;#39;prev_height&amp;#39; for the next recursive call is the current cell&amp;#39;s height&lt;/span&gt;
                &lt;span class="c1"&gt;# This ensures we only &amp;quot;flow upstream&amp;quot; (or stay level)&lt;/span&gt;
                &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;new_r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;visited_matrix&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

        &lt;span class="c1"&gt;# 1. Start DFS from cells bordering the Pacific Ocean&lt;/span&gt;
        &lt;span class="c1"&gt;# Top row (r=0)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;can_reach_pacific&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# -1 ensures any height is valid to start from the ocean&lt;/span&gt;

        &lt;span class="c1"&gt;# Left column (c=0), excluding (0,0) which is covered by the top row loop&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;can_reach_pacific&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# 2. Start DFS from cells bordering the Atlantic Ocean&lt;/span&gt;
        &lt;span class="c1"&gt;# Bottom row (r=m-1)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;can_reach_atlantic&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Right column (c=n-1), excluding (m-1,n-1) which is covered by the bottom row loop&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="c1"&gt;# Note: iterate up to m-2 to avoid (m-1, n-1) duplicate if m-1 &amp;gt;= 0&lt;/span&gt;
            &lt;span class="n"&gt;dfs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;can_reach_atlantic&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


        &lt;span class="c1"&gt;# 3. Collect the result: cells reachable by both oceans&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;can_reach_pacific&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;can_reach_atlantic&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
                    &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h2 id="complexity-analysis"&gt;Complexity Analysis&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; &lt;code&gt;O(m * n)&lt;/code&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We perform two independent DFS traversals. Each DFS visits every cell at most once. For each cell, we perform constant work (checking neighbors).&lt;/li&gt;
&lt;li&gt;The final iteration to collect results also takes &lt;code&gt;O(m * n)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Therefore, the total time complexity is proportional to the number of cells in the grid.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; &lt;code&gt;O(m * n)&lt;/code&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We use two boolean matrices (&lt;code&gt;can_reach_pacific&lt;/code&gt; and &lt;code&gt;can_reach_atlantic&lt;/code&gt;), each of size &lt;code&gt;m x n&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The recursion stack for DFS in the worst case could go &lt;code&gt;O(m * n)&lt;/code&gt; deep (if the grid is a long, winding path).&lt;/li&gt;
&lt;li&gt;Thus, the total space complexity is &lt;code&gt;O(m * n)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="why-this-approach-shines"&gt;Why This Approach Shines&lt;/h2&gt;
&lt;p&gt;This "flow upstream" or "reverse traversal" technique is incredibly powerful for problems where you need to find reachability from multiple sources. Instead of &lt;code&gt;(m*n)&lt;/code&gt; separate traversals, you consolidate it into a fixed number of traversals (in this case, two: one for Pacific, one for Atlantic). It dramatically reduces the time complexity and is a common optimization strategy in graph problems.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;LeetCode 417, "Pacific Atlantic Water Flow," is a fantastic problem that reinforces the power of strategic thinking in algorithm design. By transforming the problem from a "flow downhill" to a "flow upstream" perspective, we unlock an efficient DFS/BFS solution. This problem is more than just coding; it's about understanding how to model real-world scenarios (like water flow) into graph problems and applying optimal traversal techniques.&lt;/p&gt;
&lt;p&gt;Keep practicing, keep exploring different graph traversal variations, and you'll be well-prepared to conquer similar challenges in your next coding interview! Happy coding!&lt;/p&gt;</content><category term="Algorithms &amp; Data Structures"/><category term="LeetCode"/><category term="Graph Theory"/><category term="Coding Interview"/><category term="Graph Algorithms"/><media:content height="675" medium="image" type="image/webp" url="https://analyticsdrive.tech/images/2026/02/leetcode-417-pacific-atlantic-water-flow-dfs-solution.webp" width="1200"/><media:title type="plain">Conquering LeetCode 417: A Deep Dive into Pacific Atlantic Water Flow with DFS</media:title><media:description type="plain">Dive into LeetCode 417 (Pacific Atlantic Water Flow). Learn an efficient DFS/BFS approach to solve this classic graph traversal problem and ace your coding interviews!</media:description></entry></feed>