Shortest Unique prefix for every word | Practice | GeeksforGeeks

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.
Example 1:
Input: 
N = 4
arr[] = {"zebra", "dog", "duck", "dove"}
Output: z dog du dov
Explanation: 
z => zebra 
dog => dog 
duck => du 
dove => dov 

Example 2:
Input: 
N = 3
arr[] =  {"geeksgeeks", "geeksquiz",
                       "geeksforgeeks"};
Output: geeksg geeksq geeksf
Explanation: 
geeksgeeks => geeksg 
geeksquiz => geeksq 
geeksforgeeks => geeksf
0
therishabhkumar0012 weeks ago
need help
class tr{   public:   int num;   tr* children[26];   bool last ;   tr(){       num = 1;       for(int i=0;i<26;i++)children[i]=NULL;       last = false;   }};
class Solution{   public:   void insert(tr* root, string word){       if(word.size()==0){           root->last=true;           return ;       }       tr *child = new tr;       if(root->children[word[0]-'a']==NULL){           root->children[word[0]-'a'] = child;           insert(child,word.substr(1));       }else{           root->children[word[0]-'a']->num++;           insert(root->children[word[0]-'a'],word.substr(1));       }       return ;   }      void go(tr* root, string temp, vector<string> &ans,string& x){       if(root!=NULL&&temp.size()!=0)x.push_back(temp[0]);       else return;       if(root->children[temp[0]-'a']->num==1||temp.size()==1){           ans.push_back(x);           return ;       }       go(root->children[temp[0]-'a'],temp.substr(1),ans,x);   }      vector<string> findPrefixes(string arr[], int n)   {       vector<string > ans;       tr  *root = new tr;       for(int i=0;i<n;i++)insert(root,arr[i]);       string temp="";       for(int i=0;i<n;i++){           go(root,arr[i],ans,temp);           temp.clear();       }       return ans;   } };
giving error(Abort signal from abort(3) (SIGABRT)) at testcase number 10004.
+2
arthurshelby1 month ago
😉✌️🇮🇳❄️
struct Trie{
    Trie *dict[26];
    int count;
    Trie(){
        count=0;
        for(int i=0;i<26;i++){ //clearing for the next testcase
           dict[i]=NULL;
        }
    }
};
class Solution
{
    public:
    vector<string>v;
    Trie *root=new Trie();
    void make(string s )
    {
        Trie *cur=root;
        for(int i=0;i<s.length();i++)
        {
            if(cur->dict[s[i]-'a']==NULL)
            cur->dict[s[i]-'a']=new Trie();
            cur->dict[s[i]-'a']->count++;
            cur=cur->dict[s[i]-'a'];
        }
    }
    vector<string> findPrefixes(string arr[], int n)
    {
        //code here
        for(int i=0;i<n;i++)
        make(arr[i]);
        for(int i=0;i<n;i++)
        {
            Trie *cur=root;
            for(int j=0;j<arr[i].size();j++)
            {
                    cur=cur->dict[arr[i][j]-'a'];
                    if(cur->count==1)
                    {
                    v.push_back(arr[i].substr(0,j+1));
                    break;
                    }
            }
        }
        return v;
    }
};
+1
goelharsh491 month ago
JAVA Efficient Solution
// { Driver Code Starts
//Initial Template for Java

import java.io.*;
import java.util.*;

class GFG {
    public static void main(String args[]) throws IOException {
        BufferedReader read =
            new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(read.readLine());
        while (t-- > 0) {
            int N = Integer.parseInt(read.readLine());
            
            String arr[] = read.readLine().split(" ");

            Solution ob = new Solution();
            String[] res = ob.findPrefixes(arr,N);
            
            for(int i=0; i<res.length; i++)
                System.out.print(res[i] + " ");
            System.out.println();
        }
    }
}// } Driver Code Ends


//User function Template for Java

class Solution {
    static String[] findPrefixes(String[] a, int n) {
        Trie root = new Trie();
        String[] ans = new String[n];
        
        for(int i=0;i<n;i++){
            Trie temp = root;
            
            for(int j = 0;j<a[i].length();j++){
                char c = a[i].charAt(j);
                
                if(temp.a[c-'a'] == null )
                    temp.a[c-'a'] = new Trie();
                
                temp = temp.a[c-'a'];
                temp.end++;
            }
        }
        
        for(int i=0;i<n;i++){
            Trie temp = root;
            int j = 0;
            
            while(temp.end != 1){
                char c = a[i].charAt(j);
                temp = temp.a[c-'a'];
                j++;
            }
            
            ans[i] = a[i].substring(0,j);
        }
        
        return ans;
    }
}

class Trie{
    Trie a[] = new Trie[26];
    int end;
}
0
sequeirahansel
This comment was deleted.
0
sequeirahansel
This comment was deleted.
0
anushkay009212 months ago
  class TrieNode {   TrieNode children [] = new TrieNode [26];   boolean isEndOfWord = false ;   }class Solution {       static  void insert(TrieNode root, String key)   {     TrieNode node = root ;   for( int i = 0; i < key.length(); i++)   {       if(node.children[key.charAt(i) - 'a'] == null)       {           TrieNode newNode = new TrieNode ();           node.children[key.charAt(i) - 'a'] = newNode;       }       node = node.children[key.charAt(i) - 'a'] ;   }      node.isEndOfWord = true;
}
static String search(TrieNode root, String key){    int start = 0;   int end = 0;  TrieNode node = root ;  int count;      for( int i = 0; i < key.length(); i++)   {       count = 0 ;       for(int j= 0 ; j < 26 ; j++)       {            if( node.children [j] != null ) count ++;       }       if (count > 1 && i!=0 ) end = i ;       node = node.children[key.charAt(i) - 'a'];          }     String prefix = key.substring(start, end +1);     return prefix;  }   static String[] findPrefixes(String[] arr, int N) {              TrieNode root = new TrieNode ();       for(int i = 0; i< arr.length; i++)        {           insert (root, arr[i]);       }       String [] result = new String [N] ;       for (int i = 0 ; i < arr.length; i++ )       {           result [i] = search(root, arr[i]);       }       return result ;   }};
+1
lindan1232 months ago
struct TrieNode
    {
        int count;
        TrieNode* child[26];
        TrieNode()
        {
            count=0;
            for(int i=0;i<26;i++)
            {
                child[i]=NULL;
            }
        }
    };
class Solution
{
    public:
    TrieNode* root = new TrieNode();
    
    vector<string> findPrefixes(string arr[], int n)
    {
        vector<string> vec;
        
        for(int i=0;i<n;i++)
        {
            maketree(arr[i],root);
        }
        
        for(int i=0;i<n;i++)
        {
            string s = arr[i];
            TrieNode* curr = root;
            string ans="";
            for(int j=0;j<s.length();j++)
            {
                int ind = s[j]-'a';
                 curr = curr->child[ind];
                if(curr->count==1)
                {
                    vec.push_back(s.substr(0,j+1));
                    break;
                }
               
            }
        }
        return vec;
    }
    
    void maketree(string s,TrieNode* root)
    {
        TrieNode* curr = root;
        for(int i=0;i<s.length();i++)
        {
            if(curr->child[s[i]-'a']==NULL)
            {
                curr->child[s[i]-'a'] = new TrieNode();
            }
            curr->child[s[i]-'a']->count++;
            curr = curr->child[s[i]-'a'];
        }
    }
   
    
};
Time Taken : 0.4
Cpp
0
himanshujain4572 months ago
Can Anyone Tell Why Can't Be This Output of TC-1:
z d du do 
+3
abhishek2061a2 months ago
Simple C++ Solution using Trie
 
class Trie{
  
  Trie* child[26];
  int startWith;
  int endWith;
  
  public:
  
  Trie()
  {
      fill_n(this->child, 26, nullptr);
      startWith = 0;
      endWith = 0;
  }
  
  void insert(string word)
  {
      Trie* root = this;
      
      for(char it : word)
      {
          int i = it-'a';
          
          if(!root->child[i])
            root->child[i] = new Trie();
        
        root = root->child[i];
        root->startWith++;
      }
      
      root->endWith++;
  }
  
  string find(string word)
  {
      Trie* root = this;
      string ans;
      
      for(char it : word)
      {
          ans.push_back(it);
          
          int i = it-'a';
          
          root = root->child[i];
          
          if(root->startWith == 1)
          break;
      }
      
      return ans;
  }
  
};

class Solution
{
    public:
    vector<string> findPrefixes(string arr[], int n)
    {
        //code here
        Trie* root = new Trie();
        vector<string> ans;
        
        for(int i=0; i<n; i++)
        root->insert(arr[i]);
        
        for(int i=0; i<n; i++)
        ans.push_back(root->find(arr[i]));
        
        return ans;
    }
    
};
0
mayankkannojia293 months ago
Java 2/5.8
class Node{   char data;   int count;   HashMap<Character,Node> values;   Node(char d){       this.data = d;       values = new HashMap<>();       count=1;   }}
class Solution {   static String[] findPrefixes(String[] str, int N) {       HashMap<Character,Node> hash = new HashMap<>();       for(int i = 0;i<N;i++){           Node c = new Node(str[i].charAt(0));           if(hash.containsKey(c.data)){               c = hash.get(c.data);               c.count += 1;           }           else hash.put(c.data,c);           for(int j = 1;j<str[i].length();j++){               if(c.values.containsKey(str[i].charAt(j))){                   c = c.values.get(str[i].charAt(j));                   c.count += 1;               }               else{                   Node temp = new Node(str[i].charAt(j));                   c.values.put(str[i].charAt(j),temp);                   c = temp;               }           }       }       String[] b = new String[N];       for(int i = 0;i<N;i++){           Node n = hash.get(str[i].charAt(0));           for(int j = 0;j<str[i].length();j++){               if(n.count == 1){                   b[i] = str[i].substring(0,j+1);                   break;               }else if(j != str[i].length()-1) n = n.values.get(str[i].charAt(j+1));               else b[i] = str[i];           }       }       return b;   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.