Lexicographically Smallest and Largest

Last Updated : 13 Jun, 2026

Given an array of strings s[]. You need to find the lexicographically smallest and largest.

Examples:

Input: s[] = [a , ab , abc]
Output: [a, abc]
Explanation: Lexicographically smallest is "a" and largest is "abc".

Input: s[] = [abc , abc]
Output: [abc, abc]
Explanation: Lexicographically smallest is "abc" and largest is also "abc".

Try It Yourself
redirect icon

[Naive Approach] Using Sorting - O(n * m * log n) Time O(1) Space

The idea is to sort all the strings in lexicographical order. After sorting, the first string becomes the lexicographically smallest and the last string becomes the lexicographically largest. Return these two strings as the answer.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<string> orderString(vector<string> &s)
{
    // sorting the strings lexicographically.
    sort(s.begin(), s.end());

    // returning smallest and largest strings.
    return {s.front(), s.back()};
}

// Driver Code
int main()
{
    vector<string> s = {"abc", "abc"};

    vector<string> ans = orderString(s);

    cout << "[" << ans[0] << ", " << ans[1] << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class GfG {

    // sorting the strings lexicographically.
    public static ArrayList<String>
    orderString(ArrayList<String> s)
    {
        Collections.sort(s);

        // returning smallest and largest strings.
        ArrayList<String> res = new ArrayList<>();
        res.add(s.get(0));
        res.add(s.get(s.size() - 1));

        return res;
    }

    // Driver Code
    public static void main(String[] args)
    {
        ArrayList<String> s
            = new ArrayList<>(Arrays.asList("abc", "abc"));

        ArrayList<String> ans = orderString(s);

        System.out.println("[" + ans.get(0) + ", "
                           + ans.get(1) + "]");
    }
}
Python
def orderString(s):
    # sorting the strings lexicographically.
    s.sort()

    # returning smallest and largest strings.
    return [s[0], s[-1]]


# Driver Code
if __name__ == "__main__":
    s = ["abc", "abc"]

    ans = orderString(s)

    print("[" + ans[0] + ", " + ans[1] + "]")
C#
using System;
using System.Collections.Generic;
using System.Linq;

class GfG {
    static List<string> orderString(List<string> s)
    {
        // sorting the strings lexicographically.
        s.Sort();

        // returning smallest and largest strings.
        return new List<string>{ s.First(), s.Last() };
    }

    // Driver Code
    static void Main(string[] args)
    {
        List<string> s = new List<string>{ "abc", "abc" };

        List<string> ans = orderString(s);

        Console.WriteLine("[" + ans[0] + ", " + ans[1]
                          + "]");
    }
}
JavaScript
// sorting the strings lexicographically.
function orderString(s)
{
    s.sort();

    // returning smallest and largest strings.
    return [ s[0], s[s.length - 1] ];
}

// Driver Code
let s = [ "abc", "abc" ];

let ans = orderString(s);

console.log("[" + ans[0] + ", " + ans[1] + "]");

Output
[abc, abc]

Time Complexity: O(n * m * log n)
Auxiliary Space: O(1)

[Expected Approach] Linear Scan - O(n * m) Time O(1) Space

The idea is to traverse the array once while maintaining the indices of the lexicographically smallest and largest strings found so far. For each string, update the minimum index if it is smaller than the current minimum string, and update the maximum index if it is larger than the current maximum string. Finally, return the strings at these indices.

Let us understand with example:
Input: s[] = [abc , abc]

  • Initially, min_ind = 0 and max_ind = 0. Both point to the first string "abc".
  • For i = 1, compare s[1] = "abc" with s[min_ind] = "abc". Since both strings are equal, compare() returns 0, so min_ind remains 0.
  • Next, compare s[1] = "abc" with s[max_ind] = "abc". Again, compare() returns 0, so max_ind remains 0.
  • The traversal is complete. The smallest string is s[min_ind] = "abc" and the largest string is s[max_ind] = "abc".
  • Add these strings to the result vector and return: ["abc", "abc"].
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<string> orderString(vector<string> &s)
{
    // variables to keep track of minimum and maximum indices.
    int min_ind = 0, max_ind = 0;

    // getting size of array.
    int n = s.size();

    // iterating over the array to find minimum and maximum indices.
    for (int i = 1; i <= n - 1; i++)
    {
        // comparing current string with string at minimum index.
        // If it is smaller, updating minimum index.
        if ((s[i].compare(s[min_ind])) < 0)
            min_ind = i;

        // comparing current string with string at maximum index.
        // If it is larger, updating maximum index.
        if (s[i].compare(s[max_ind]) > 0)
            max_ind = i;
    }

    // creating a vector to store the ordered strings.
    vector<string> res;

    // adding the string at minimum index to the result vector.
    res.push_back(s[min_ind]);

    // adding the string at maximum index to the result vector.
    res.push_back(s[max_ind]);

    // returning the ordered strings.
    return res;
}

// Driver Code
int main()
{
    vector<string> s = {"abc", "abc"};

    vector<string> ans = orderString(s);

    cout << "[" << ans[0] << ", " << ans[1] << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;

public class GfG {

    public static ArrayList<String>
    orderString(ArrayList<String> s)
    {
        // variables to keep track of minimum and maximum
        // indices.
        int min_ind = 0, max_ind = 0;

        // getting size of array.
        int n = s.size();

        // iterating over the array to find minimum and
        // maximum indices.
        for (int i = 1; i <= n - 1; i++) {
            // comparing current string with string at
            // minimum index. If it is smaller, updating
            // minimum index.
            if (s.get(i).compareTo(s.get(min_ind)) < 0)
                min_ind = i;

            // comparing current string with string at
            // maximum index. If it is larger, updating
            // maximum index.
            if (s.get(i).compareTo(s.get(max_ind)) > 0)
                max_ind = i;
        }

        // creating a list to store the ordered strings.
        ArrayList<String> res = new ArrayList<>();

        // adding the string at minimum index to the result
        // list.
        res.add(s.get(min_ind));

        // adding the string at maximum index to the result
        // list.
        res.add(s.get(max_ind));

        // returning the ordered strings.
        return res;
    }

    // Driver Code
    public static void main(String[] args)
    {
        ArrayList<String> s
            = new ArrayList<>(Arrays.asList("abc", "abc"));

        ArrayList<String> ans = orderString(s);

        System.out.println("[" + ans.get(0) + ", "
                           + ans.get(1) + "]");
    }
}
Python
def orderString(s):
    # variables to keep track of minimum and maximum indices.
    min_ind = 0
    max_ind = 0

    # getting size of array.
    n = len(s)

    # iterating over the array to find minimum and maximum indices.
    for i in range(1, n):
        # comparing current string with string at minimum index.
        # If it is smaller, updating minimum index.
        if s[i] < s[min_ind]:
            min_ind = i

        # comparing current string with string at maximum index.
        # If it is larger, updating maximum index.
        if s[i] > s[max_ind]:
            max_ind = i

    # creating a list to store the ordered strings.
    res = []

    # adding the string at minimum index to the result list.
    res.append(s[min_ind])

    # adding the string at maximum index to the result list.
    res.append(s[max_ind])

    # returning the ordered strings.
    return res


# Driver Code
if __name__ == "__main__":
    s = ["abc", "abc"]

    ans = orderString(s)

    print("[" + ans[0] + ", " + ans[1] + "]")
C#
using System;
using System.Collections.Generic;

public class GfG {

    public static List<string> orderString(List<string> s)
    {
        // variables to keep track of minimum and maximum
        // indices.
        int min_ind = 0, max_ind = 0;

        // getting size of array.
        int n = s.Count;

        // iterating over the array to find minimum and
        // maximum indices.
        for (int i = 1; i <= n - 1; i++) {
            // comparing current string with string at
            // minimum index. If it is smaller, updating
            // minimum index.
            if (s[i].CompareTo(s[min_ind]) < 0)
                min_ind = i;

            // comparing current string with string at
            // maximum index. If it is larger, updating
            // maximum index.
            if (s[i].CompareTo(s[max_ind]) > 0)
                max_ind = i;
        }

        // creating a list to store the ordered strings.
        List<string> res = new List<string>();

        // adding the string at minimum index to the result
        // list.
        res.Add(s[min_ind]);

        // adding the string at maximum index to the result
        // list.
        res.Add(s[max_ind]);

        // returning the ordered strings.
        return res;
    }

    // Driver Code
    public static void Main()
    {
        List<string> s = new List<string>{ "abc", "abc" };

        List<string> ans = orderString(s);

        Console.WriteLine("[" + ans[0] + ", " + ans[1]
                          + "]");
    }
}
JavaScript
// variables to keep track of minimum and maximum indices.
function orderString(s)
{
    let min_ind = 0, max_ind = 0;

    // getting size of array.
    let n = s.length;

    // iterating over the array to find minimum and maximum
    // indices.
    for (let i = 1; i <= n - 1; i++) {
        // comparing current string with string at minimum
        // index. If it is smaller, updating minimum index.
        if (s[i].localeCompare(s[min_ind]) < 0)
            min_ind = i;

        // comparing current string with string at maximum
        // index. If it is larger, updating maximum index.
        if (s[i].localeCompare(s[max_ind]) > 0)
            max_ind = i;
    }

    // creating an array to store the ordered strings.
    let res = [];

    // adding the string at minimum index to the result
    // array.
    res.push(s[min_ind]);

    // adding the string at maximum index to the result
    // array.
    res.push(s[max_ind]);

    // returning the ordered strings.
    return res;
}

// Driver Code
let s = [ "abc", "abc" ];

let ans = orderString(s);

console.log("[" + ans[0] + ", " + ans[1] + "]");

Output
[abc, abc]

Time Complexity: O(n * m)
Auxiliary Space: O(1)

Comment