Sort an array of strings lexicographically based on prefix
Last Updated :
25 Oct, 2022
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__
Python3
# Function to print the vector
def 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 conditions
def sort(v,lst):
a = v[1]
b = v[0]
c = v[2]
# returning lexicographically smallest string
if(c<a and c<b):
lst.append(c)
# 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,len(b), b) is 0 or comp(b,0,len(a), a) is 0):
if(len(a)>len(b)):
lst.append(a)
lst.append(b)
else:
lst.append(b)
lst.append(a)
# Driver Code
# GIven vector of strings
v = [ "batman", "bat", "apple" ]
# Calling Sort STL with my_compare
# function passed as third parameter
lst = []
sort(v,lst)
# Function call to print the vector
Print(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<string> 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<string> v = new List<string>();
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
<script>
// Function to print the vector
function Print(v)
{
console.log(v);
}
function comp(a,s,e,b)
{
if (a.length >= e && b.length >= e) {
for (let 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
function compare(a,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;
}
// Driver Code
// GIven vector of strings
v = [ "batman", "bat", "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__
</script>
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
C++ Program to Sort Elements in Lexicographical Order (Dictionary Order)
Similar Reads
Sort an Array of Strings in Lexicographical order Given an array of strings arr[] of size n, the task is to sort all the strings in lexicographical order. Examples:Input: arr[] = ["banana", "apple", "cherry"]Output: ["apple", "banana", "cherry"]Explanation: All strings are sorted alphabetically. "apple" comes before "banana", and "banana" before "c
11 min read
Sort a string lexicographically by reversing a substring Given a string S consisting of N lowercase characters, the task is to find the starting and the ending indices ( 0-based indexing ) of the substring of the given string S that needed to be reversed to make the string S sorted. If it is not possible to sort the given string S by reversing any substri
12 min read
Sort a list of strings in lexicographical order in Python We are given a list of strings and our task is to sort them in lexicographical order, which means alphabetical order either from A to Z (ascending) or Z to A (descending). This is a common operation when organizing or comparing strings in Python. For example:Input: ["banana", "apple", "cherry", "dat
2 min read
Lexicographically smallest string obtained after concatenating array Given n strings, concatenate them in an order that produces the lexicographically smallest possible string. Examples: Input : a[] = ["c", "cb", "cba"] Output : cbacbc Possible strings are ccbcba, ccbacb, cbccba, cbcbac, cbacbc and cbaccb. Among all these strings, cbacbc is the lexicographically smal
5 min read
Lexicographical concatenation of all substrings of a string Given a string, find the concatenation of all substrings in lexicographic order.Examples:Input : s = "abc"Output : aababcbbccThe substrings of s in lexicographic order are "a", "b", "c", "ab", "abc", "bc". Concatenation of substrings is "a"+"ab"+"abc"+"b"+"bc"+"c" = "aababcbbcc".Input : s = "cba"Out
7 min read
Lexicographically smallest string with given string as prefix Given an array arr[] consisting of N strings and a string S if size M, the task is to find the lexicographically smallest string consisting of the string S as the prefix. If there doesn't exist any string starting with prefix S then print "-1". Examples: Input: arr[] = {"apple", "appe", "apl", "aapl
6 min read