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

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 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 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.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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] + " ");
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right



Output:

The shortest unique prefixes in sorted order are :
dog dov du z 

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 result array, we can get the index of the corresponding string from hashmap and add the prefix to that index.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print shortest unique prefixes
// for every word in order of appearance of words
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];
  
        Arrays.fill(res, "");
  
        /* hashmap to store the indexes */
        HashMap<String, Integer> hm =
                        new HashMap<String, Integer>();
  
        for (int i = 0; i < size; i++)
            hm.put(a[i], i);
  
        /* 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;
        }
  
        /* get the index of a[0] from HashMap */
        res[ hm.get(a[0]) ] = 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 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[ hm.get(a[i]) ] = temp_prefix;
            else
                res[ hm.get(a[i]) ] = 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 */
        String sec_last = a[size-2];
        String last = a[size-1];
  
        j = 0;
        while (j < Math.min( sec_last.length()-1, last.length()-1))
        {
            if (sec_last.charAt(j) == last.charAt(j) )
                j++;
            else
                break;
        }
  
        res[ hm.get(last) ] = 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 are :");
        for (int i=0; i < output.length; i++)
            System.out.print( output[i] + " ");
    }
}

chevron_right


Output:

The shortest unique prefixes are :
z dog du dov 

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 contribute.geeksforgeeks.org or mail your article to contribute@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.



My Personal Notes arrow_drop_up

Improved By : princi singh



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.