Find shortest unique prefix for every word in a given list | Set 2 (Using Sorting) - GeeksforGeeks

08 Feb, 2022
Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is a prefix of another. Output the shortest unique prefixes in sorted order.
Input  : {"zebra", "dog", "duck", "dove"}
Output : z, dog, dov, du
Explanation: dog => dog
             dove = dov 
             duck = du
             z   => zebra 

Input: {"geeksgeeks", "geeksquiz", "geeksforgeeks"}
Output: geeksf, geeksg, geeksq
We have discussed a Trie based approach in the below post. Find shortest unique prefix for every word in a given list | Set 1 (Using Trie)In this post, a sorting based approach is discussed. On comparing the string with 2 other most similar strings in the array, we can find its shortest unique prefix. For example, if we sort the array {“zebra”, “dog”, “duck”, “dove”}, we get {“dog”, “dove”, “duck”, “zebra”}. The shortest unique prefix for the string “dove” can be found as: Compare “dove” to “dog” –> unique prefix for dove is “dov” Compare “dove” to “duck” –> unique prefix for dove is “do” Now, the shortest unique prefix for “dove” is the one with greater length between “dov” and “do”. So, it is “dov”. The shortest unique prefix for the first and last string can be found by comparing them with only 1 most similar neighbor on right and left, respectively. 
We can sort the array of strings and keep on doing this for every string of the array.  
C++
Java
Python3
C#
// C++ program to print shortest unique prefixes// for every word.#include <bits/stdc++.h>using namespace std; vector<string> uniquePrefix(vector<string> &a){    int size = a.size();     /* create an array to store the results */    vector<string> res(size);     /* sort the array of strings */    sort(a.begin(), a.end());     /* compare the first string with its only right    neighbor */    int j = 0;    while (j < min(a[0].length() - 1, a[1].length() - 1))    {        if (a[0][j] == a[1][j])            j++;        else            break;    }    int ind = 0;    res[ind++] = a[0].substr(0, j + 1);     /* Store the unique prefix of a[1] from its left neighbor */    string temp_prefix = a[1].substr(0, j + 1);    for (int i = 1; i < size - 1; i++)    {        /* compute common prefix of a[i] unique from        its right neighbor */        j = 0;        while (j < min(a[i].length() - 1, a[i + 1].length() - 1))        {            if (a[i][j] == a[i + 1][j])                j++;            else                break;        }         string new_prefix = a[i].substr(0, j + 1);         /* compare the new prefix with previous prefix */        if (temp_prefix.length() > new_prefix.length())            res[ind++] = temp_prefix;        else            res[ind++] = new_prefix;         /* store the prefix of a[i+1] unique from its        left neighbour */        temp_prefix = a[i + 1].substr(0, j + 1);    }     /* compute the unique prefix for the last string    in sorted array */    j = 0;    string sec_last = a[size - 2];     string last = a[size - 1];     while (j < min(sec_last.length() - 1, last.length() - 1))    {        if (sec_last[j] == last[j])            j++;        else            break;    }     res[ind] = last.substr(0, j + 1);    return res;} // Driver Codeint main(){    vector<string> input = {"zebra", "dog", "duck", "dove"};    vector<string> output = uniquePrefix(input);    cout << "The shortest unique prefixes in sorted order are : \n";     for (auto i : output)        cout << i << ' ';     return 0;} // This code is contributed by// sanjeev2552
// Java program to print shortest unique prefixes// for every word.import java.io.*;import java.util.*; class GFG{    public String[] uniquePrefix(String[] a)    {        int size = a.length;         /* create an array to store the results */        String[] res = new String[size];         /* sort the array of strings */        Arrays.sort(a);         /* compare the first string with its only right           neighbor */        int j = 0;        while (j < Math.min(a[0].length()-1, a[1].length()-1))        {            if (a[0].charAt(j)==a[1].charAt(j))                j++;            else                break;        }          int ind = 0;        res[ind++] = a[0].substring(0, j+1);         /* Store the unique prefix of a[1] from its left neighbor */        String temp_prefix = a[1].substring(0, j+1);        for (int i = 1; i < size-1; i++)        {            /* compute common prefix of a[i] unique from               its right neighbor */            j = 0;            while (j < Math.min( a[i].length()-1, a[i+1].length()-1 ))            {                if (a[i].charAt(j) == a[i+1].charAt(j))                    j++;                else                    break;            }             String new_prefix = a[i].substring(0, j+1);             /* compare the new prefix with previous prefix */            if (temp_prefix.length() > new_prefix.length() )                res[ind++] = temp_prefix;            else                res[ind++] = new_prefix;             /* store the prefix of a[i+1] unique from its               left neighbour */            temp_prefix = a[i+1].substring(0, j+1);        }         /* compute the unique prefix for the last string           in sorted array */        j = 0;        String sec_last = a[size-2] ;         String last = a[size-1];         while (j < Math.min( sec_last.length()-1, last.length()-1))        {            if (sec_last.charAt(j) == last.charAt(j))                j++;            else                break;        }         res[ind] = last.substring(0, j+1);        return res;    }     /* Driver Function to test other function */    public static void main(String[] args)    {        GFG gfg = new GFG();         String[] input = {"zebra", "dog", "duck", "dove"};         String[] output = gfg.uniquePrefix(input);        System.out.println( "The shortest unique prefixes" +                               " in sorted order are :");         for (int i=0; i < output.length; i++)            System.out.print( output[i] + " ");    }}
# Python3 program to print shortest unique prefixes# for every word.def uniquePrefix(a):         size = len(a)     # Create an array to store the results    res = [0] * (size)     # Sort the array of strings */    a = sorted(a)     # Compare the first with its only right    # neighbor    j = 0    while (j < min(len(a[0]) - 1, len(a[1]) - 1)):        if (a[0][j] == a[1][j]):            j += 1        else:            break     ind = 0    res[ind] = a[0][0:j + 1]    ind += 1     # Store the unique prefix of a[1]    # from its left neighbor    temp_prefix = a[1][0:j + 1]    for i in range(1, size - 1):                 # Compute common prefix of a[i] unique from        # its right neighbor        j = 0                 while (j < min(len(a[i]) - 1, len(a[i + 1]) - 1)):            if (a[i][j] == a[i + 1][j]):                j += 1            else:                break         new_prefix = a[i][0:j + 1]         # Compare the new prefix with previous prefix        if (len(temp_prefix) > len(new_prefix)):            res[ind] = temp_prefix            ind += 1        else:            res[ind] = new_prefix            ind += 1         # Store the prefix of a[i+1] unique from its        # left neighbour        temp_prefix = a[i + 1][0:j + 1]     # Compute the unique prefix for the last    # in sorted array    j = 0    sec_last = a[size - 2]     last = a[size - 1]     while (j < min(len(sec_last) - 1, len(last) - 1)):        if (sec_last[j] == last[j]):            j += 1        else:            break     res[ind] = last[0:j + 1]    return res # Driver Codeif __name__ == '__main__':         input = [ "zebra", "dog", "duck", "dove" ]    output = uniquePrefix(input)         print("The shortest unique prefixes " +          "in sorted order are : ")     for i in output:        print(i, end = " ")         # This code is contributed by mohit kumar 29
// C# program to print shortest unique prefixes// for every word.using System;     class GFG{    public String[] uniquePrefix(String[] a)    {        int size = a.Length;         /* create an array to store the results */        String[] res = new String[size];         /* sort the array of strings */        Array.Sort(a);         /* compare the first string with its only right        neighbor */        int j = 0;        while (j < Math.Min(a[0].Length - 1, a[1].Length - 1))        {            if (a[0][j] == a[1][j])                j++;            else                break;        }          int ind = 0;        res[ind++] = a[0].Substring(0, j + 1);         /* Store the unique prefix of a[1] from its left neighbor */        String temp_prefix = a[1].Substring(0, j + 1);        for (int i = 1; i < size - 1; i++)        {            /* compute common prefix of a[i] unique from            its right neighbor */            j = 0;            while (j < Math.Min( a[i].Length - 1, a[i + 1].Length - 1 ))            {                if (a[i][j] == a[i + 1][j])                    j++;                else                    break;            }             String new_prefix = a[i].Substring(0, j+1);             /* compare the new prefix with previous prefix */            if (temp_prefix.Length > new_prefix.Length )                res[ind++] = temp_prefix;            else                res[ind++] = new_prefix;             /* store the prefix of a[i+1] unique from its            left neighbour */            temp_prefix = a[i+1].Substring(0, j+1);        }         /* compute the unique prefix for the last string        in sorted array */        j = 0;        String sec_last = a[size-2] ;         String last = a[size-1];         while (j < Math.Min( sec_last.Length-1, last.Length-1))        {            if (sec_last[j] == last[j])                j++;            else                break;        }         res[ind] = last.Substring(0, j+1);        return res;    }     /* Driver code */    public static void Main(String[] args)    {        GFG gfg = new GFG();         String[] input = {"zebra", "dog", "duck", "dove"};         String[] output = gfg.uniquePrefix(input);        Console.WriteLine( "The shortest unique prefixes" +                            " in sorted order are :");         for (int i = 0; i < output.Length; i++)            Console.Write( output[i] + " ");    }} // This code is contributed by Princi Singh
Output: 
The shortest unique prefixes in sorted order are :
dog dov du z 
Another Python approach:If we want to output the prefixes as the order of strings in the input array, we can store the string and its corresponding index in the hashmap. While adding the prefix to the result array, we can get the index of the corresponding string from the hashmap and add the prefix to that index.
Python3
#Python program to print shortest unique prefix for every word in a list a=['dogs','dove','duck','zebra']r=[]j=0while(j<min(len(a[0]),len(a[1]))):    if(a[0][j]==a[1][j]):        j+=1    else:        break i=0r.append(a[0][0:j+1])x=a[1][0:j+1] for i in range(1,len(a)-1):    j=0    while(j<min(len(a[i]),len(a[i+1]))):        if a[i][j]==a[i+1][j]:            j+=1        else:            break     y=a[i][0:j+1]    if(len(x)>len(y)):        r.append(x)    else:        r.append(y)    x=a[i+1][0:j+1]     j=0l=a[len(a)-2]k=a[len(a)-1] while(j<min(len(l),len(k))):    if ( l[j]==k[j]):        j+=1    else:        break         r.append(k[0:j+1])print("The shortest unique prefixes are :")for i in range(0,len(r)):  print(r[i],end=' ')    #This code is contributed by Saahith Reddy
Output: 
The shortest unique prefixes are :
dog dov du z
For a more efficient solution, we can use Trie as discussed in this post.This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
princi singh
sanjeev2552
reddysaahithm
mohit kumar 29
simmytarika5
Sorting
Strings
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
C++ Program for QuickSort
Stability in sorting algorithms
Quick Sort vs Merge Sort
Sorting in Java
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4