Lexicographically smallest string formed by replacing characters according to the given relation
Last Updated :
23 Jul, 2025
Given a string Str of N characters and two strings S1 and S2 of equal length where S1[i] and S2[i] are related to each other, the task is to find the lexicographically smallest string that can be obtained by replacing characters in Str with their related character.
Examples:
Input: S1 = "rat", S2 = "cbb", Str = "trrb"
Output: acca
Explanation: For the given S1 and S2, the characters that are related to each other are (r, c), (a, b), and (t, b).
Hence, in the given string, r can be replaced by c;
b can be replaced by a, and t can be replaced by a.
Hence, Str = "bcca". Here, b again can be replaced by a.
Therefore, the final value of Str = "acca", which is the smallest possible.
Input: S1 = "abc", S2 = "xyz", Str = "pqr"
Output: pqr
Naive Approach: The given problem can be solved by creating an undirected graph where an edge connecting (x, y) represents a relation between characters x and y. Thereafter, for each character in the given string, traverse the graph using DFS and find the smallest character among the connected vertices of the current character and replace them.
Time Complexity: O(N * M), where M represents the size of S1 or S2.
Auxiliary space: O(M)
Efficient Approach: The above approach can be optimally solved using the Disjoint Set Data Structure. The idea is to group all the characters having a relation into a same group which can be efficiently done using DSU. Here, it can be noted that during the union operation in DSU, the parent of a node should be chosen as the smallest character in the group to achieve the smallest lexicographic order.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int N = 26;
// Class to implements all functions
// of the Disjoint Set Data Structure
class DisjointSet {
public:
int size;
int parent[N];
char chars[N];
DisjointSet()
{
size = 26;
for (int i = 0; i < size; i++) {
parent[i] = i;
}
for (int i = 0; i < 26; i++) {
chars[i] = 'a' + i;
}
}
int find_parent(int x)
{
if (parent[x] == x) {
return x;
}
parent[x] = find_parent(parent[x]);
return (parent[x]);
}
void union_fun(int u, int v)
{
// find parent
int p1 = find_parent(u);
int p2 = find_parent(v);
// if not same
if (p1 != p2) {
// if p2 smaller than p1
// then make parent p2
if (p2 < p1) {
parent[p1] = p2;
// make parent p1
}
else {
parent[p2] = p1;
}
}
}
};
// Function to find the lexicographically
// smallest string formed by replacing
// characters according to given relation
string smallestLexStr(string S1, string S2, string Str)
{
// Create an object of DSU
DisjointSet ds;
int M = S1.length();
// Iterate through all given relations
for (int i = 0; i < M; i++) {
// find ascii value of each character
// and subtract from ascii value 'a'
// so that index value is between 0-25
int idx1 = S1[i] - 'a';
int idx2 = S2[i] - 'a';
// take union of both indices
ds.union_fun(idx1, idx2);
}
// Iterate through the string
for (int i = 0; i < Str.length(); i++) {
// Find the smallest character
// replacement among all relations
int idx = ds.find_parent(Str[i] - 'a');
Str[i] = ds.chars[idx];
}
// Return the answer
return Str;
}
// Driver code
int main()
{
string S1 = "rat";
string S2 = "cbb";
string Str = "trrb";
cout << smallestLexStr(S1, S2, Str) << endl;
return 0;
}
// This code is contributed by lokeshpotta20.
Java
// Java program to implement above approach
import java.util.*;
public class GFG {
// Function to find the lexicographically
// smallest string formed by replacing
// characters according to given relation
static String smallestLexStr(String S1, String S2,
String Str)
{
// Create an object of DSU
DisjointSet ds = new DisjointSet();
int M = S1.length();
// Iterate through all given relations
for (int i = 0; i < M; i++) {
// find ascii value of each character
// and subtract from ascii value a
// so that index value between 0-25
int idx1 = (int)(S1.charAt(i)) - (int)('a');
int idx2 = (int)(S2.charAt(i)) - (int)('a');
// take union of both indices
ds.union(idx1, idx2);
}
// Convert String into list of characters
char[] arr = Str.toCharArray();
// Iterate through the list of characters
for (int i = 0; i < arr.length; i++) {
// Find the smallest character
// replacement among all relations
int idx = ds.find_parent((int)(arr[i])
- (int)('a'));
arr[i] = ds.chars[idx];
}
// Convert the list back to a string
Str = "";
for (char x : arr) {
Str += x;
}
// Return Answer
return Str;
}
// Driver code
public static void main(String[] args)
{
String S1 = "rat";
String S2 = "cbb";
String Str = "trrb";
System.out.println(smallestLexStr(S1, S2, Str));
}
}
// Class to implements all functions
// of the Disjoint Set Data Structure
class DisjointSet {
public int size;
public int[] parent;
public char[] chars;
public DisjointSet()
{
size = 26;
parent = new int[size];
for (int i = 0; i < size; i++) {
parent[i] = i;
}
chars = new char[size];
for (int i = 0; i < 26; i++) {
chars[i] = (char)(i + 97);
}
}
public int find_parent(int x)
{
if (parent[x] == x) {
return x;
}
parent[x] = find_parent(parent[x]);
return (parent[x]);
}
public void union(int u, int v)
{
// find parent
int p1 = find_parent(u);
int p2 = find_parent(v);
// if not same
if (p1 != p2) {
// if p2 smaller than p1
// then make parent p2
if (p2 < p1) {
parent[p1] = p2;
// make parent p1
}
else {
parent[p2] = p1;
}
}
}
}
// This code is contributed by karandeep1234
Python3
# Python code to implement the above approach
# Class to implements all functions
# of the Disjoint Set Data Structure
class DisjointSet:
def __init__(self):
self.size = 26
self.parent = [i for i in range(self.size)]
self.chars = [chr(i+97) for i in range(self.size)]
def find_parent(self, x):
if (self.parent[x] == x):
return (x)
self.parent[x] = self.find_parent(self.parent[x])
return (self.parent[x])
def union(self, u, v):
# find parent
p1 = self.find_parent(u)
p2 = self.find_parent(v)
# if not same
if (p1 != p2):
# if p2 smaller than p1
# then make parent p2
if (p2 < p1):
self.parent[p1] = p2
# make parent p1
else:
self.parent[p2] = p1
# Function to find the lexicographically
# smallest string formed by replacing
# characters according to given relation
def smallestLexStr(S1, S2, Str):
# Create an object of DSU
ds = DisjointSet()
M = len(S1)
# Iterate through all given relations
for i in range(M):
# find ascii value of each character
# and subtract from ascii value a
# so that index value between 0-25
idx1 = ord(S1[i]) - ord('a')
idx2 = ord(S2[i]) - ord('a')
# take union of both indices
ds.union(idx1, idx2)
# Convert String into list of characters
Str = list(Str)
# Iterate through the list of characters
for i in range(len(Str)):
# Find the smallest character
# replacement among all relations
idx = ds.find_parent(ord(Str[i]) - ord('a'))
Str[i] = ds.chars[idx]
# Convert the list back to a string
Str = "".join(Str)
# Return Answer
return Str
# Driver Code
if __name__ == "__main__":
S1 = "rat"
S2 = "cbb"
Str = "trrb"
print(smallestLexStr(S1, S2, Str))
C#
// C# program to implement above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
// Function to find the lexicographically
// smallest string formed by replacing
// characters according to given relation
static string smallestLexStr(string S1, string S2, string Str){
// Create an object of DSU
DisjointSet ds = new DisjointSet();
int M = S1.Length;
// Iterate through all given relations
for (int i = 0 ; i < M ; i++){
// find ascii value of each character
// and subtract from ascii value a
// so that index value between 0-25
int idx1 = (int)(S1[i]) - (int)('a');
int idx2 = (int)(S2[i]) - (int)('a');
// take union of both indices
ds.union(idx1, idx2);
}
// Convert String into list of characters
List<char> arr = new List<char>(Str);
// Iterate through the list of characters
for (int i = 0 ; i < arr.Count ; i++){
// Find the smallest character
// replacement among all relations
int idx = ds.find_parent((int)(arr[i]) - (int)('a'));
arr[i] = ds.chars[idx];
}
// Convert the list back to a string
Str = "";
foreach (char x in arr){
Str += x;
}
// Return Answer
return Str;
}
// Driver code
public static void Main(string[] args){
string S1 = "rat";
string S2 = "cbb";
string Str = "trrb";
Console.WriteLine(smallestLexStr(S1, S2, Str));
}
}
// Class to implements all functions
// of the Disjoint Set Data Structure
public class DisjointSet{
public int size;
public int[] parent;
public char[] chars;
public DisjointSet(){
size = 26;
parent = new int[size];
for(int i = 0 ; i < size ; i++){
parent[i] = i;
}
chars = new char[size];
for(int i = 0 ; i < 26 ; i++){
chars[i] = (char)(i+97);
}
}
public int find_parent(int x){
if (parent[x] == x){
return x;
}
parent[x] = find_parent(parent[x]);
return (parent[x]);
}
public void union(int u, int v){
// find parent
int p1 = find_parent(u);
int p2 = find_parent(v);
// if not same
if (p1 != p2){
// if p2 smaller than p1
// then make parent p2
if (p2 < p1){
parent[p1] = p2;
// make parent p1
}else{
parent[p2] = p1;
}
}
}
}
// This code is contributed by subhamgoyal2014.
JavaScript
// Javascript program to implement above approach
// Class to implements all functions
// of the Disjoint Set Data Structure
class DisjointSet {
constructor() {
this.size = 26;
this.parent = new Array(this.size);
for (let i = 0; i < this.size; i++) {
this.parent[i] = i;
}
this.chars = new Array(this.size);
for (let i = 0; i < 26; i++) {
this.chars[i] = String.fromCharCode(i + 97);
}
}
find_parent(x) {
if (this.parent[x] == x) {
return x;
}
this.parent[x] = this.find_parent(this.parent[x]);
return (this.parent[x]);
}
union(u, v) {
// find parent
let p1 = this.find_parent(u);
let p2 = this.find_parent(v);
// if not same
if (p1 != p2) {
// if p2 smaller than p1
// then make parent p2
if (p2 < p1) {
this.parent[p1] = p2;
// make parent p1
}
else {
this.parent[p2] = p1;
}
}
}
}
// Function to find the lexicographically
// smallest let formed by replacing
// characters according to given relation
function smallestLexStr(S1, S2, Str) {
// Create an object of DSU
let ds = new DisjointSet();
let M = S1.length;
// Iterate through all given relations
for (let i = 0; i < M; i++) {
// find ascii value of each character
// and subtract from ascii value a
// so that index value between 0-25
let idx1 = (S1.charAt(i)).charCodeAt(0) - 'a'.charCodeAt(0);
let idx2 = (S2.charAt(i)).charCodeAt(0) - 'a'.charCodeAt(0);
// take union of both indices
ds.union(idx1, idx2);
}
// Convert let into list of characters
let arr = Str.split("");
// Iterate through the list of characters
for (let i = 0; i < arr.length; i++) {
// Find the smallest character
// replacement among all relations
let idx = ds.find_parent(arr[i].charCodeAt(0)
- 'a'.charCodeAt(0));
arr[i] = ds.chars[idx];
}
// Convert the list back to a string
Str = "";
for (x of arr) {
Str += x;
}
// Return Answer
return Str;
}
// Driver code
let S1 = "rat";
let S2 = "cbb";
let Str = "trrb";
console.log(smallestLexStr(S1, S2, Str));
// This code is contributed by Saurabh Jaiswal
Time Complexity: O(N)
Auxiliary space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem