Skip to content
Related Articles

Related Articles

Sort an array of strings lexicographically based on prefix

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 31 Aug, 2021

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.


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

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

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 (, b.size(), b) == 0
        ||, a.size(), a) == 0)
        return a.size() & gt;
    // Else return lexicographically
    // smallest string
    else return a & lt;

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 (, b.size(), b) == 0
        ||, a.size(), a) == 0)
        return a.size() > b.size();
    // Else return lexicographically
    // smallest string
        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
    return 0;




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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!