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”, “geeksforgeeks”, “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.
**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() & gt;
b.size();
// Else return lexicographically
// smallest string
**else**
**return**
a & lt;
b;
}
Below is the implementation of the above approach:
// 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;
}
Output:
apple
batman
bat
Time Complexity:_ O(N*log N)_
Auxiliary Space:_ O(1)_
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#arrays #sorting #strings #lexicographic-ordering #prefix