AntInLoop

Union-Find (Disjoint Set Union / DSU) Code Implementations

Production-ready Union-Find (Disjoint Set Union / DSU) data structure implementations in C++, Python, Java, and JavaScript on AntInLoop.

Study Union-Find (Disjoint Set Union / DSU) Guide ยท Launch Visualizer

CPP Implementation

#include <bits/stdc++.h>
using namespace std;

// Trie node structure
class TrieNode {
public:
    TrieNode* children[26];
    bool isEndOfWord;

    // Node constructor
    TrieNode() {
        isEndOfWord = false;
        for (int i = 0; i < 26; i++)
            children[i] = NULL;
    }
};

// Trie structure
class Trie {
private:
    TrieNode* root;

public:
    // Trie constructor
    Trie() {
        root = new TrieNode();
    }

    // Function to insert a word into the Trie
    void insert(string key) {
        TrieNode* pCrawl = root;
        for (int i = 0; i < key.length(); i++) {
            int index = key[i] - 'a';
            if (!pCrawl->children[index])
                pCrawl->children[index] = new TrieNode();
            pCrawl = pCrawl->children[index];
        }
        pCrawl->isEndOfWord = true;
    }

    // Function to search a word in the Trie
    bool search(string key) {
        TrieNode* pCrawl = root;
        for (int i = 0; i < key.length(); i++) {
            int index = key[i] - 'a';
            if (!pCrawl->children[index])
                return false;
            pCrawl = pCrawl->children[index];
        }
        return (pCrawl != NULL && pCrawl->isEndOfWord);
    }
};