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() & gt; b.size(); // Else return lexicographically // smallest string else return a & lt; b; } |
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; } |
apple batman bat
Time Complexity: O(N*log N)
Auxiliary Space: O(1)