Lexicographically smallest String formed by extracting single character
Last Updated :
20 Dec, 2023
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
Time Complexity: O(number of words * length of each word)
Auxiliary Space: O(1) (Considering frequency array space as constant)
Similar Reads
Lexicographically smallest String by removing exactly K characters Given a string s consisting of only lowercase characters, the task is to find the lexicographically smallest string after removing exactly k characters from the string. But you have to modify the value of k, i.e., if the length of the string is a power of 2, reduce k by half, else multiply k by 2. Y
15 min read
Lexicographically smallest string formed by removing at most one character Given a string s, the task is to find the lexicographically smallest string that can be formed by removing at most one character from the given string. Examples: Input: s = "abcda" Output: "abca"Explanation: One can remove 'd' to get "abca" which is the lexicographically smallest string possible. In
4 min read
Lexicographically smallest string formed by removing duplicates Given a string S consisting of lowercase alphabets, the task is to find the lexicographically smallest string that can be obtained by removing duplicates from the given string S. Examples: Input: S = "yzxyz"Output: xyzExplanation: Removing the duplicate characters at indices 0 and 1 in the given str
7 min read
Find the lexicographically smallest string by prepending characters Two Players A and B are playing a game using a non-empty string S of length N having lowercase English Alphabets. The length of string S is even. Each player also has a string of their own, initially empty. In one move, a player takes either the first or the last character of the string S, removes i
15+ min read
Maximum occurring lexicographically smallest character in a String Given a string containing lowercase characters. The task is to print the maximum occurring character in the input string. If 2 or more characters appear the same number of times, print the lexicographically (alphabetically) lowest (first) character. Examples: Input: test sample Output: e Explanation
6 min read