# Sort an array of strings lexicographically based on prefix

Given an array of strings arr[] of size N, the task is to sort the array of strings in lexicographical order and if while sorting for any two string A and string B, if string A is prefix of string B then string B should come in the sorted order.

Examples:

Input: arr[] = {“sun”, “moon”, “mock”}
Output:
mock
moon
sun
Explanation:
The lexicographical sorting is mock, moon, and sun.

Input: arr[] = {“geeks”, “geeksfor”, “geeksforgeeks”}
Output:
geeksforgeeks
geeksfor
geeks

Approach: The idea is to sort the given array of strings using the inbuilt sort function using the below comparator function. The comparator function used to check if any string occurs as a substring in another string using compare() function in C++ then, it should arrange them in decreasing order of their length.

## C++

 bool my_compare(string a, string b){    // If any string is a substring then    // return the size with greater length    if (a.compare(0, b.size(), b) == 0        || b.compare(0, a.size(), a) == 0)        return a.size() > b.size();     // Else return lexicographically    // smallest string    else return a < b;}

## Java

 public static boolean my_compare(String a, String b){     // If any string is a substring then  // return the size with greater length  if (a.compareTo(b) == 0 || b.compareTo(a) == 0)    return a.length() > b.length();   // Else return lexicographically  // smallest string  else {    if (a.length() < b.length())      return true;  }  return false;} // This code is contributed by akashish__

## Python3

 def my_compare(a, b):       # If any string is a substring then    # return the size with greater length  if (a.compare(0, b.length, b) is 0 or b.compare(0, a.length, a) is 0):    return a.length > b.length;     # Else return lexicographically    # smallest string  else:    return a < b;    # This code is contributed by akashish__

## C#

 // C# implementation of the approachusing System;using System.Collections.Generic; public static bool my_compare(string a, string b){     // If any string is a substring then  // return the size with greater length  if (a.CompareTo(b) == 0 || b.CompareTo(a) == 0)    return a.Length > b.Length;   // Else return lexicographically  // smallest string  else {    if (a.Length < b.Length)      return true;  }  return false;} // This code is contributed by sanjoy_62.

## Javascript

 function my_compare(a,b){    // If any string is a substring then    // return the size with greater length    if (a.compare(0, b.length, b) == 0        || b.compare(0, a.length, a) == 0)        return a.length > b.length;     // Else return lexicographically    // smallest string    else    return a < b;   } // This code is contributed by ksam24000.

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach #include using namespace std; // Function to print the vectorvoid Print(vector v){    for (auto i : v)        cout << i << endl;} // Comparator function to sort the// array of string wrt given conditionsbool my_compare(string a, string b){    // Check if a string is present as    // prefix in another string, then    // compare the size of the string    // and return the larger size    if (a.compare(0, b.size(), b) == 0        || b.compare(0, a.size(), a) == 0)         return a.size() > b.size();     // Else return lexicographically    // smallest string    else        return a < b;} // Driver Codeint main(){    // GIven vector of strings    vector v = { "batman", "bat", "apple" };     // Calling Sort STL with my_compare    // function passed as third parameter    sort(v.begin(), v.end(), my_compare);     // Function call to print the vector    Print(v);    return 0;}

## Java

 /*package whatever //do not write package name here */ import java.io.*;import java.lang.*;import java.util.*; class GFG {   public static int comp(String a, int s, int e, String b)  {    if (a.length() >= e && b.length() >= e) {      for (int i = s; i < e; i++) {        if (a.charAt(i) != b.charAt(i))          return -1;      }    }    else      return -1;     return 0;  }   // Function to print the vector  public static void Print(List v)  {    for (String i : v)      System.out.println(i);  }   public static void main(String[] args)  {         // GIven vector of strings    List v = new ArrayList();    v.add("batman");    v.add("bat");    v.add("apple");     // Calling Sort STL with my_compare    // function passed as third parameter    Collections.sort(v, new Comparator() {      @Override      public int compare(final String a, String b)      {        // Check if a string is present as        // prefix in another string, then        // compare the size of the string        // and return the larger size        if (comp(a, 0, b.length(), b) == 0            || comp(b, 0, a.length(), a) == 0) {          if (a.length() > b.length()) {            return 1;          }          else            return 1;        }         // Else return lexicographically        // smallest string        else {          if (a.length() < b.length())            return -1;        }        return -1;      }    });     // Function call to print the vector    Print(v);  }} // This code is contributed by akashish__

## Python3

 # Function to print the vectordef Print(v):  print(v) def comp(a,s,e,b):  if (len(a) >= e and len(b) >= e):    for i in range(s,e):      if (a[i] is not b[i]):        return -1  else:    return -1   return 0 # Comparator function to sort the# array of string wrt given conditionsdef sort(v,lst):     a = v[1]  b = v[0]  c = v[2]  # returning lexicographically smallest string  if(clen(b)):      lst.append(a)      lst.append(b)    else:      lst.append(b)      lst.append(a)   # Driver Code# GIven vector of stringsv = [ "batman", "bat", "apple" ] # Calling Sort STL with my_compare# function passed as third parameterlst = []sort(v,lst) # Function call to print the vectorPrint(lst) # This code is contributed by akashish__

## C#

 using System;using System.Collections.Generic; public class GFG {   // Function to print the  public static void Print(List v)  {    for (int i = 0; i < v.Count; i++) {      Console.WriteLine(v[i]);    }  }   public static int comp(String a, int s, int e, String b)  {    if (a.Length >= e && b.Length >= e) {      for (int i = s; i < e; i++) {        if (a[i] != b[i])          return -1;      }    }    else      return -1;     return 0;  }   // Comparator function to sort the  // array of string wrt given conditions  public static int compare(String a, String b)  {    // Check if a string is present as    // prefix in another string, then    // compare the size of the string    // and return the larger size    if (comp(a, 0, b.Length, b) == 0        || comp(b, 0, a.Length, a) == 0) {      if (a.Length > b.Length) {        return -1;      }      else        return 1;    }     // Else return lexicographically    // smallest string    else {      if (a.Length > b.Length)        return 1;    }    return -1;  }   static public void Main()  {     // Driver Code    // Given List of strings    List v = new List();    v.Add("batman");    v.Add("bat");    v.Add("apple");     // Calling Sort STL with my_compare    // function passed as third parameter    v.Sort(compare);     // Function call to print the vector    Print(v);  }} // This code is contributed by akashish__

## Javascript



Output:
apple
batman
bat

Time Complexity: O(N*log N)
Auxiliary Space: O(1)

Previous
Next