Skip to content
Related Articles

Related Articles

Sort an array of strings lexicographically based on prefix

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 29 Sep, 2022
View Discussion
Improve Article
Save Article

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 approach
using 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 <bits/stdc++.h>
using namespace std;
 
// Function to print the vector
void Print(vector<string> v)
{
    for (auto i : v)
        cout << i << endl;
}
 
// Comparator function to sort the
// array of string wrt given conditions
bool 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 Code
int main()
{
    // GIven vector of strings
    vector<string> 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<String> v)
  {
    for (String i : v)
      System.out.println(i);
  }
 
  public static void main(String[] args)
  {
     
    // GIven vector of strings
    List<String> v = new ArrayList<String>();
    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<String>() {
      @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__

Output: 

apple
batman
bat

 

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

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!