Open In App

Lexicographically smallest String formed by extracting single character

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string array S, the task is to find the lexicographically smallest string that can be formed by extracting a single character in each string from the string array S.

Example:

Input: S = [“xy”, “fd”]
Output: “dx”
Explanation: The possible strings formed by extracting a single character from each string are [“xf”, “fx”, “xd”, “dx”, “yf”, “fy”, “yd”, “dy”]. The lexicographically smallest string obtained is “dx”.

Approach: To solve the problem follow the below idea:

The idea is to extract the smallest character in each string and then rearrange them to get the lexicographically smallest string.

Steps to solve the problem:

  • Create a frequency array to store the frequency of each smallest character in the array of strings.
  • Iterate over each string and find out the smallest character and add it to the frequency array.
  • Traverse the frequency array and append the characters to the final string.

Below is the code for the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Funcion to find the lexicographically smallest string
string LexicographicallySmallest(vector<string>& words)
{
    // Initializing the frequency array
    vector<int> frequency(26, 0);
 
    // Traversing the each string to
    // find the smallest character
    for (string s : words) {
        int mini = 27;
        char best_char = 'z';
        for (char c : s) {
            if (mini > (c - 'a')) {
                mini = c - 'a';
                best_char = c;
            }
        }
        frequency[best_char - 'a'] += 1;
    }
 
    string result = "";
 
    // Traversing the frequency array to find the result
    for (int i = 0; i < 26; i++) {
        while (frequency[i]--) {
            result += char(i + 'a');
        }
    }
    return result;
}
 
// Drivers code
int main()
{
    vector<string> words = { "xy", "fd" };
 
    // Function Call
    cout << LexicographicallySmallest(words);
    return 0;
}


Java




import java.util.*;
 
public class LexicographicallySmallest {
    public static String
        lexicographicallySmallest(String[] words)
    {
        // Initializing the frequency array
        int[] frequency = new int[26];
 
        // Traversing each string to find the smallest
        // character
        for (String s : words) {
            int mini = 27;
            char bestChar = 'z';
            for (char c : s.toCharArray()) {
                if (mini > (c - 'a')) {
                    mini = c - 'a';
                    bestChar = c;
                }
            }
            frequency[bestChar - 'a'] += 1;
        }
 
        StringBuilder result = new StringBuilder();
 
        // Traversing the frequency array to find the result
        for (int i = 0; i < 26; i++) {
            while (frequency[i] > 0) {
                result.append((char)(i + 'a'));
                frequency[i] -= 1;
            }
        }
 
        return result.toString();
    }
 
    public static void main(String[] args)
    {
        String[] words = { "xy", "fd" };
 
        // Function Call
        System.out.println(
            lexicographicallySmallest(words));
    }
}


Python3




def lexicographically_smallest(words):
    # Initializing the frequency array
    frequency = [0] * 26
 
    # Traversing each string to find the smallest character
    for s in words:
        mini = 27
        best_char = 'z'
        for c in s:
            if mini > (ord(c) - ord('a')):
                mini = ord(c) - ord('a')
                best_char = c
        frequency[ord(best_char) - ord('a')] += 1
 
    result = ""
 
    # Traversing the frequency array to find the result
    for i in range(26):
        while frequency[i] > 0:
            result += chr(i + ord('a'))
            frequency[i] -= 1
 
    return result
 
# Driver code
if __name__ == "__main__":
    words = ["xy", "fd"]
 
    # Function Call
    print(lexicographically_smallest(words))


C#




using System;
using System.Text;
 
public class GFG
{
    public static string LexicographicallySmallest(string[] words)
    {
        // Initializing the frequency array
        int[] frequency = new int[26];
 
        // Traversing each string to find the smallest character
        foreach (string s in words)
        {
            int mini = 27;
            char bestChar = 'z';
            foreach (char c in s.ToCharArray())
            {
                if (mini > (c - 'a'))
                {
                    mini = c - 'a';
                    bestChar = c;
                }
            }
            frequency[bestChar - 'a'] += 1;
        }
 
        StringBuilder result = new StringBuilder();
 
        // Traversing the frequency array to find the result
        for (int i = 0; i < 26; i++)
        {
            while (frequency[i] > 0)
            {
                result.Append((char)(i + 'a'));
                frequency[i] -= 1;
            }
        }
 
        return result.ToString();
    }
 
    public static void Main(string[] args)
    {
        string[] words = { "xy", "fd" };
 
        // Function Call
        Console.WriteLine(LexicographicallySmallest(words));
    }
}


Javascript




// Javascript program for the above approach
 
// Function to find the lexicographically smallest string
function LexicographicallySmallest(words) {
    // Initializing the frequency array
    const frequency = new Array(26).fill(0);
 
    // Traversing each string to find the smallest character
    for (const s of words) {
        let mini = 27;
        let best_char = 'z';
        for (const c of s) {
            if (mini > c.charCodeAt(0) - 'a'.charCodeAt(0)) {
                mini = c.charCodeAt(0) - 'a'.charCodeAt(0);
                best_char = c;
            }
        }
        frequency[best_char.charCodeAt(0) - 'a'.charCodeAt(0)] += 1;
    }
 
    let result = '';
 
    // Traversing the frequency array to find the result
    for (let i = 0; i < 26; i++) {
        while (frequency[i]--) {
            result += String.fromCharCode(i + 'a'.charCodeAt(0));
        }
    }
    return result;
}
 
// Driver code
const words = ["xy", "fd"];
 
// Function call
console.log(LexicographicallySmallest(words));
 
// This code is contributed by Susobhan Akhuli


Output

dx








Time Complexity: O(number of words * length of each word)
Auxiliary Space: O(1) (Considering frequency array space as constant)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads