The Wayback Machine - https://web.archive.org/web/20240907074314/https://www.geeksforgeeks.org/longest-common-prefix-using-trie/
Open In App

Longest Common Prefix using Trie

Last Updated : 15 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
38.66%
13.4K

Given a set of strings, find the longest common prefix.

Input  : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}
Output : "gee"

Input  : {"apple", "ape", "april"}
Output : "ap"

Previous Approaches : Word by Word Matching , Character by Character Matching, Divide and Conquer , Binary Search. In this article, an approach using Trie date structure is discussed. Steps:

  • Insert all the words one by one in the trie. After inserting we perform a walk on the trie.
  • In this walk, go deeper until we find a node having more than 1 children(branching occurs) or 0 children (one of the string gets exhausted). This is because the characters (nodes in trie) which are present in the longest common prefix must be the single child of its parent, i.e- there should not be branching in any of these nodes.

Algorithm Illustration considering strings as – “geeksforgeeks”, “geeks”, “geek”, “geezer” Longest-Common-Prefix-using-Trie

C++




// A Program to find the longest common
// prefix of the given words
 
#include<bits/stdc++.h>
using namespace std;
 
// Alphabet size (# of symbols)
#define ALPHABET_SIZE (26)
 
// Converts key current character into index
// use only 'a' through 'z' and lower case
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
 
// Trie node
struct TrieNode
{
    struct TrieNode *children[ALPHABET_SIZE];
 
    // isLeaf is true if the node represents
    // end of a word
    bool isLeaf;
};
 
// Returns new trie node (initialized to NULLs)
struct TrieNode *getNode(void)
{
    struct TrieNode *pNode = new TrieNode;
 
    if (pNode)
    {
        int i;
 
        pNode->isLeaf = false;
 
        for (i = 0; i < ALPHABET_SIZE; i++)
            pNode->children[i] = NULL;
    }
 
    return pNode;
}
 
// If not present, inserts the key into the trie
// If the key is a prefix of trie node, just marks leaf node
void insert(struct TrieNode *root, string key)
{
    int length = key.length();
    int index;
 
    struct TrieNode *pCrawl = root;
 
    for (int level = 0; level < length; level++)
    {
        index = CHAR_TO_INDEX(key[level]);
        if (!pCrawl->children[index])
            pCrawl->children[index] = getNode();
 
        pCrawl = pCrawl->children[index];
    }
 
    // mark last node as leaf
    pCrawl->isLeaf = true;
}
 
// Counts and returns the number of children of the
// current node
int countChildren(struct TrieNode *node, int *index)
{
    int count = 0;
    for (int i=0; i<ALPHABET_SIZE; i++)
    {
        if (node->children[i] != NULL)
        {
            count++;
            *index = i;
        }
    }
    return (count);
}
 
// Perform a walk on the trie and return the
// longest common prefix string
string walkTrie(struct TrieNode *root)
{
    struct TrieNode *pCrawl = root;
    int index;
    string prefix;
 
    while (countChildren(pCrawl, &index;) == 1 &&
            pCrawl->isLeaf == false)
    {
        pCrawl = pCrawl->children[index];
        prefix.push_back('a'+index);
    }
    return (prefix);
}
 
// A Function to construct trie
void constructTrie(string arr[], int n, struct TrieNode *root)
{
    for (int i = 0; i < n; i++)
        insert (root, arr[i]);
    return;
}
 
// A Function that returns the longest common prefix
// from the array of strings
string commonPrefix(string arr[], int n)
{
    struct TrieNode *root = getNode();
    constructTrie(arr, n, root);
 
    // Perform a walk on the trie
    return walkTrie(root);
}
 
// Driver program to test above function
int main()
{
    string arr[] = {"geeksforgeeks", "geeks",
                    "geek", "geezer"};
    int n = sizeof (arr) / sizeof (arr[0]);
 
    string ans = commonPrefix(arr, n);
 
    if (ans.length())
        cout << "The longest common prefix is "
             << ans;
    else
        cout << "There is no common prefix";
    return (0);
}


Java




// Java Program to find the longest common
// prefix of the given words
public class Longest_common_prefix {
     
    // Alphabet size (# of symbols)
    static final int ALPHABET_SIZE = 26;
      
    // Trie node
    static class TrieNode
    {
        TrieNode[] children = new TrieNode[ALPHABET_SIZE];
      
        // isLeaf is true if the node represents
        // end of a word
        boolean isLeaf;
         
        // constructor
        public TrieNode() {
            isLeaf = false;
            for (int i = 0; i < ALPHABET_SIZE; i++)
                children[i] = null;
        }
    };
      
    static TrieNode root;
    static int indexs;
      
    // If not present, inserts the key into the trie
    // If the key is a prefix of trie node, just marks
    // leaf node
    static void insert(String key)
    {
        int length = key.length();
        int index;
      
        TrieNode pCrawl = root;
      
        for (int level = 0; level < length; level++)
        {
            index = key.charAt(level) - 'a';
            if (pCrawl.children[index] == null)
                pCrawl.children[index] = new TrieNode();
      
            pCrawl = pCrawl.children[index];
        }
      
        // mark last node as leaf
        pCrawl.isLeaf = true;
    }
      
    // Counts and returns the number of children of the
    // current node
    static int countChildren(TrieNode node)
    {
        int count = 0;
        for (int i=0; i<ALPHABET_SIZE; i++)
        {
            if (node.children[i] != null)
            {
                count++;
                indexs = i;
            }
        }
        return (count);
    }
      
    // Perform a walk on the trie and return the
    // longest common prefix string
    static String walkTrie()
    {
        TrieNode pCrawl = root;
        indexs = 0;
        String prefix = "";
      
        while (countChildren(pCrawl) == 1 &&
                pCrawl.isLeaf == false)
        {
            pCrawl = pCrawl.children[indexs];
            prefix += (char)('a' + indexs);
        }
        return prefix;
    }
      
    // A Function to construct trie
    static void constructTrie(String arr[], int n)
    {
        for (int i = 0; i < n; i++)
            insert (arr[i]);
        return;
    }
      
    // A Function that returns the longest common prefix
    // from the array of strings
    static String commonPrefix(String arr[], int n)
    {
        root = new TrieNode();
        constructTrie(arr, n);
      
        // Perform a walk on the trie
        return walkTrie();
    }
      
    // Driver program to test above function
    public static void main(String args[])
    {
        String arr[] = {"geeksforgeeks", "geeks",
                        "geek", "geezer"};
        int n = arr.length;
      
        String ans = commonPrefix(arr, n);
      
        if (ans.length() != 0)
            System.out.println("The longest common prefix is "+ans);
        else
            System.out.println("There is no common prefix");
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python 3 program to find the longest common prefix
ALPHABET_SIZE = 26
indexs = 0
class TrieNode:
    # constructor
    def __init__(self):
        self.isLeaf = False
        self.children = [None]*ALPHABET_SIZE
 
# Function to facilitate insertion in Trie
# If not present, insert the node in the Trie
def insert(key, root):
    pCrawl = root
    for level in range(len(key)):
        index = ord(key[level]) - ord('a')
        if pCrawl.children[index] == None:
            pCrawl.children[index] = TrieNode()
        pCrawl = pCrawl.children[index]
    pCrawl.isLeaf = True
 
# Function to construct Trie
def constructTrie(arr, n, root):
    for i in range(n):
        insert(arr[i], root)
 
# Counts and returns number of children of the node
def countChildren(node):
    count = 0
    for i in range(ALPHABET_SIZE):
        if node.children[i] != None:
            count +=1
            # Keeping track of diversion in the trie
            global indexs
            indexs = i
    return count
     
# Perform walk on trie and return longest common prefix
def walkTrie(root):
    pCrawl = root
    prefix = ""
    while(countChildren(pCrawl) == 1 and pCrawl.isLeaf == False):
        pCrawl = pCrawl.children[indexs]
        prefix += chr(97 + indexs)
    return prefix or -1
 
# Function that returns longest common prefix
def commonPrefix(arr, n, root):
    constructTrie(arr, n, root)
    return walkTrie(root)
 
# Driver code to test the code
n = 4
arr = ["geeksforgeeks", "geeks", "geek", "geezer"]
root = TrieNode()
print(commonPrefix(arr,n, root))
 
# This code is Contributed by Akshay Jain (DA-IICT)


C#




// C# Program to find the longest common
// prefix of the given words
using System;
     
public class Longest_common_prefix
{
     
    // Alphabet size (# of symbols)
    static readonly int ALPHABET_SIZE = 26;
     
    // Trie node
    public class TrieNode
    {
        public TrieNode[] children = new TrieNode[ALPHABET_SIZE];
     
        // isLeaf is true if the node represents
        // end of a word
        public bool isLeaf;
         
        // constructor
        public TrieNode()
        {
            isLeaf = false;
            for (int i = 0; i < ALPHABET_SIZE; i++)
                children[i] = null;
        }
    };
     
    static TrieNode root;
    static int indexs;
     
    // If not present, inserts the key into the trie
    // If the key is a prefix of trie node, just marks
    // leaf node
    static void insert(String key)
    {
        int length = key.Length;
        int index;
     
        TrieNode pCrawl = root;
     
        for (int level = 0; level < length; level++)
        {
            index = key[level] - 'a';
            if (pCrawl.children[index] == null)
                pCrawl.children[index] = new TrieNode();
     
            pCrawl = pCrawl.children[index];
        }
     
        // mark last node as leaf
        pCrawl.isLeaf = true;
    }
     
    // Counts and returns the number of children of the
    // current node
    static int countChildren(TrieNode node)
    {
        int count = 0;
        for (int i = 0; i < ALPHABET_SIZE; i++)
        {
            if (node.children[i] != null)
            {
                count++;
                indexs = i;
            }
        }
        return (count);
    }
     
    // Perform a walk on the trie and return the
    // longest common prefix string
    static String walkTrie()
    {
        TrieNode pCrawl = root;
        indexs = 0;
        String prefix = "";
     
        while (countChildren(pCrawl) == 1 &&
                pCrawl.isLeaf == false)
        {
            pCrawl = pCrawl.children[indexs];
            prefix += (char)('a' + indexs);
        }
        return prefix;
    }
     
    // A Function to construct trie
    static void constructTrie(String []arr, int n)
    {
        for (int i = 0; i < n; i++)
            insert (arr[i]);
        return;
    }
     
    // A Function that returns the longest common prefix
    // from the array of strings
    static String commonPrefix(String []arr, int n)
    {
        root = new TrieNode();
        constructTrie(arr, n);
     
        // Perform a walk on the trie
        return walkTrie();
    }
     
    // Driver program to test above function
    public static void Main(String []args)
    {
        String []arr = {"geeksforgeeks", "geeks",
                        "geek", "geezer"};
        int n = arr.Length;
     
        String ans = commonPrefix(arr, n);
     
        if (ans.Length != 0)
            Console.WriteLine("The longest common prefix is "+ans);
        else
            Console.WriteLine("There is no common prefix");
    }
}
 
// This code contributed by Rajput-Ji


Javascript




<script>
    // Javascript Program to find the longest common
    // prefix of the given words
     
    const ALPHABET_SIZE = 26;
     
    // Converts key current character into index
    // use only 'a' through 'z' and lower case
    const CHAR_TO_INDEX = (c) => c.charCodeAt(0) - 'a'.charCodeAt(0);
     
    // Trie node
    class TrieNode {
      constructor() {
        this.children = Array(ALPHABET_SIZE).fill(null);
        this.isLeaf = false;
      }
    }
     
    // Returns new trie node (initialized to NULLs)
    const getNode = () => new TrieNode();
     
    // If not present, inserts the key into the trie
    // If the key is a prefix of trie node, just marks leaf node
    const insert = (root, key) => {
      let length = key.length;
      let index;
     
      let pCrawl = root;
     
      for (let level = 0; level < length; level++) {
        index = CHAR_TO_INDEX(key[level]);
        if (!pCrawl.children[index]) {
          pCrawl.children[index] = getNode();
        }
     
        pCrawl = pCrawl.children[index];
      }
     
      // mark last node as leaf
      pCrawl.isLeaf = true;
    };
     
    // Counts and returns the number of children of the
    // current node
    const countChildren = (node, index) => {
      let count = 0;
      for (let i = 0; i < ALPHABET_SIZE; i++) {
        if (node.children[i] != null) {
          count++;
          index[0] = i;
        }
      }
      return count;
    };
     
    // Perform a walk on the trie and return the
    // longest common prefix string
    const walkTrie = (root) => {
      let pCrawl = root;
      let index = [];
      let prefix = "";
     
      while (countChildren(pCrawl, index) === 1 && !pCrawl.isLeaf) {
        pCrawl = pCrawl.children[index[0]];
        prefix += String.fromCharCode("a".charCodeAt(0) + index[0]);
      }
      return prefix;
    };
     
    // A Function to construct trie
    function constructTrie(arr, n, root) {
      for (let i = 0; i < n; i++) {
        insert(root, arr[i]);
      }
      return;
    };
     
    // A Function that returns the longest common prefix
    // from the array of strings
    function commonPrefix(arr, n) {
      let root = getNode();
      constructTrie(arr, n, root);
     
      // Perform a walk on the trie
      return walkTrie(root);
    };
     
    // Driver program to test above function
      let arr = ["geeksforgeeks", "geeks", "geek", "geezer"];
      let n = arr.length;
     
      let ans = commonPrefix(arr, n);
     
      if (ans.length) {
        document.write("The longest common prefix is "+ans);
      }
      else
      {
          document.write("There is no common prefix");
      }
         
        // This code is contributed by Aman Kumar.
</script>


Output :

The longest common prefix is gee

Time Complexity : Inserting all the words in the trie takes O(MN) time and performing a walk on the trie takes O(M) time, where-

N = Number of strings
M = Length of the largest string

Auxiliary Space: To store all the strings we need to allocate O(26*M*N) ~ O(MN) space for the Trie.  



Similar Reads

Longest prefix matching - A Trie based solution in Java
Given a dictionary of words and an input string, find the longest prefix of the string which is also a word in dictionary. Examples: Let the dictionary contains the following words: {are, area, base, cat, cater, children, basement} Below are some input/output examples: -------------------------------------- Input String Output ---------------------
4 min read
Find shortest unique prefix for every word in a given list | Set 1 (Using Trie)
Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another. Examples: Input: arr[] = {"zebra", "dog", "duck", "dove"} Output: dog, dov, du, z Explanation: dog =&gt; dog dove =&gt; dov duck =&gt; du zebra =&gt; z Input: arr[] = {"geeksgeeks", "geeksquiz", "geeksforge
11 min read
Longest Common Prefix using Linked List
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Previous Approaches: Word by Word Matching, Character by Character Matching, Divide and Conquer, Binary Search, Using Trie Data Structure Below is an algorithm to solve
14 min read
Longest Common Prefix using Word by Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended PracticeLongest Common Prefix in an ArrayTry It! We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest co
15 min read
Longest Common Prefix using Character by Character Matching
Given a set of strings, find the longest common prefix. Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We have discussed word by word matching algorithm in previous post.In this algorithm, instead
13 min read
Longest Common Prefix using Divide and Conquer Algorithm
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" We have discussed word by word matching and character by character matching algorithms.In this algorithm, a divide and conquer approach is discussed. We first divide th
7 min read
Longest Common Prefix using Binary Search
Given a set of strings, the tasks is to find the longest common prefix using Binary Search. Input: str = {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output: "gee" Explanation: All the given strings have "gee" prefix common in them, which is the longest them. Input: {"apple", "ape", "april"} Output: "ap" Some other approaches to Longest Common Pref
10 min read
Longest Common Prefix using Sorting
Given an array of strings strs[]. The task is to return the longest common prefix among each and every strings present in the array. If there's no prefix common in all the strings, return "-1". Examples: Input: strs[] = ["geeksforgeeks", "geeks", "geek", "geezer"]Output: geeExplanation: "gee" is the longest common prefix in all the given strings. I
6 min read
Javascript Program To Find Longest Common Prefix Using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"}Output: "gee"Input: {"apple", "ape", "april"}Output: "ap"The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {"apple", "ape", "ze
2 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.Now let us introduce
3 min read
Longest Common Prefix Matching | Set-6
Given a set of strings, find the longest common prefix. Examples: Input: str[] = {geeksforgeeks, geeks, geek, geezer} Output: gee Input: str[] = {apple, ape, april} Output: ap Previous Approaches: Set1 | Set2 | Set3 | Set4 | Set5 Approach: Sort the given set of N strings.Compare the first and last string in the sorted array of strings.The string wi
6 min read
Find the longest common prefix between two strings after performing swaps on second string
Given two strings [Tex]a [/Tex]and [Tex]b [/Tex]. Find the longest common prefix between them after performing zero or more operations on string [Tex]b [/Tex]. In each operation, you can swap any two letters.Examples: Input : a = "here", b = "there" Output : 4 The 2nd string can be made "heret" by just swapping characters and thus the longest prefi
6 min read
Construct an Array of Strings having Longest Common Prefix specified by the given Array
Given an integer array arr[] of size N, the task is to construct an array consisting of N+1 strings of length N such that arr[i] is equal to the Longest Common Prefix of ith String and (i+1)th String. Examples: Input: arr[] = {1, 2, 3} Output: {"abb", "aab", "aaa", "aaa"} Explanation: Strings "abb" and "aab" have a single character "a" as Longest C
6 min read
Length of longest common prefix possible by rearranging strings in a given array
Given an array of strings arr[], the task is to find the length of the longest common prefix by rearranging the characters of each string of the given array. Examples: Input: arr[] = {“aabdc”, “abcd”, “aacd”}Output: 3Explanation: Rearrange characters of each string of the given array such that the array becomes {“acdab”, “acdb”, “acda”}.Therefore,
8 min read
Pair of strings having longest common prefix of maximum length in given array
Given an array of strings arr[], the task is to find the pair of strings from the given array whose length of the longest common prefix between them is maximum. If multiple solutions exist, then print any one of them. Examples: Input: arr[] = {"geeksforgeeks", "geeks", "geeksforcse", } Output: (geeksforgeeks, geeksforcse) Explanation: All possible
15+ min read
Length of longest prefix anagram which are common in given two strings
Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings. Examples: Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"Output: 6Explanation: Prefixes of length 1 of string str1 and str2 are "a", and "c".Prefixes of length 2 of string
8 min read
Find minimum shift for longest common prefix
You are given two strings str1 and str2 of the same length. In a single shift, you can rotate one string (str2) by 1 element such that its 1st element becomes the last and the second one becomes the first like "abcd" will change to "bcda" after the one-shift operation. You have to find the minimum shift operation required to get the common prefix o
7 min read
Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Maximum sum increasing subsequence from a prefix and a given element after prefix is must
Given an array of n positive integers, write a program to find the maximum sum of increasing subsequence from prefix till ith index and also including a given kth element which is after i, i.e., k &gt; i. Examples : Input: arr[] = {1, 101, 2, 3, 100, 4, 5} i-th index = 4 (Element at 4th index is 100) K-th index = 6 (Element at 6th index is 5.) Outp
14 min read
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix
Given three strings S, S1, and S2, the task is to check if the number of substrings that start and end with S1 and S2 is equal to the number of substrings that start and end with S2 and S1 or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "helloworldworldhelloworld", S1 = "hello", S2 = "world"Output: NoExpla
8 min read
Maximum prefix sum which is equal to suffix sum such that prefix and suffix do not overlap
Given an array arr[] of N Positive integers, the task is to find the largest prefix sum which is also the suffix sum and prefix and suffix do not overlap. Examples: Input: N = 5, arr = [1, 3, 2, 1, 4]Output: 4Explanation: consider prefix [1, 3] and suffix [4] which gives maximum prefix sum which is also suffix sum such that prefix and suffix do not
7 min read
Counting common prefix/suffix strings in two lists
Given two Lists of strings s1 and s2, you have to count the number of strings in s2 which is either a suffix or prefix of at least one string of s1. Examples: Input: s1 = ["cat", "catanddog", "lion"], s2 = ["cat", "dog", "rat"]Output: 2Explanation: String "cat" of s2 is a prefix of "catanddog"string "dog" of s2 is suffix of "catanddog" Input: s1 =
4 min read
Find position i to split Array such that prefix sum till i-1, i and suffix sum till i+1 are in GP with common ratio K
Given an array, arr[] and a positive integer K. The task is to find the position say i of the element in arr[] such that prefix sum till i-1, i and suffix sum till i+1 are in Geometric Progression with common ratio K. Examples: Input: arr[] = { 5, 1, 4, 20, 6, 15, 9, 10 }, K = 2Output: 4Explanation: The following operations are performed to get req
8 min read
Find position forming AP with prefix and suffix sum of Array with common difference D
Given an array, arr[] of size N and a positive integer D, the task is to find the position i of an element in arr[] such that the prefix sum, arr[i] and suffix sum is in arithmetic progression with common difference D, i.e. arr[i] - sum(arr[0, . . ., i-1]) = sum(arr[i+1, . . ., N-1]) - arr[i] = D. If no such position exists return -1. Examples: Inp
8 min read
Maximum number of Strings with Common Prefix of length K
Given a string array arr[] of length N, the task is to find the maximum number of strings that share a common prefix of length K. Examples: Input: arr = { { "hello", "heydeei", "hap", "hak", "paloa", "padfk", "padfla", "pada" } }, K = 4Output: 2Explanation: String padfk", "padfla" are the two string that share the common prefix of length k. Input:
8 min read
Maximum common prefix of all strings
Given array A[] of strings of size N, the task for this problem is to print the Maximum Common prefix of string 'i' with other strings from 1 to N apart from 'i' itself for all given strings from 1 to N. Given strings consists of lowercase English letters. Examples: Input: {"abc", "abb", "aac"}Output: 2 2 1Explanation: Answer for first string is tw
12 min read
Sorting array of strings (or words) using Trie | Set-2 (Handling Duplicates)
Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print all the occurrences.Examples: Input : arr[] = { "abc", "xyz", "abcd", "bcd", "abc" } Output : abc abc abcd bcd xyz Input : arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn" } Output : a for geeks geeks lea
9 min read
Implement a Dictionary using Trie
Implement a dictionary using Trie such that if the input is a string representing a word, the program prints its meaning from the prebuilt dictionary. Examples: Input: str = "map" Output: a diagrammatic representation of an area Input: str = "language" Output: the method of human communication Approach: We can use a Trie to efficiently store string
9 min read
Trie Data Structure using smart pointer and OOP in C++
We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursionIn our implementation node of a trie look like : C/C++ Code class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this
6 min read
Count inversions in an array | Set 4 ( Using Trie )
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted then inversion count is 0. If the array is sorted in reverse order that inversion count is the maximum. Two elements a[i] and a[j] form an inversion if a[i] &gt; a[j] and i &lt; j. For simplicity, we may assume that all element
12 min read