Sort strings in Lexicographical order

By | September 30, 2023

You are given n strings. You have to print them in lexicographical increasing order. Also, ensure that all of the strings should be distinct.

Examples:

Input: {"Aarav", "Arjun", "Rahul", "Rishabh", "Kunal"}
Output: {"Aarav", "Arjun", "Kunal", "Rahul", "Rishabh"}

Input: {"Vikram", "Rajat", "Abhishek", "Suresh", "Rajat"}
Output: {"Abhishek", "Rajat", "Suresh", "Vikram"}

Recommended: What is Algorithm | Introduction to Algorithms

Approach:
Actually lexicographical order is dictionary order. To determine the lexicographical order we compare the corresponding characters of two strings from left to right and when two characters different to each other then the string with large Unicode character will come later. All Uppercase letters come before lower case. Exactly the same thing is done by set it automatically sorts the strings in lexicographical order.

Below is the implementation of the above approach:

#include <bits/stdc++.h>
using namespace std;

int main() {
    // String array to sort in lexicographical increasing order
    string s[] = {"Aarav", "Arjun", "Rahul", "Rishabh", "Kunal"};

    // Initialize a set of strings
    set<string> str(s, s + 5);

    // Set iterator to iterate through the set
    set<string>::iterator it;

    // Final lexicographical increasing order of the strings
    for (it = str.begin(); it != str.end(); ++it)
        cout << *it << " ";
    
    cout << endl;

    return 0;
}

Output:

Aarav Arjun Kunal Rahul Rishabh  

Time complexity: O(nlogn)

Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.