Convert string X to an anagram of string Y with minimum replacements
Last Updated :
01 Aug, 2022
Given two strings X and Y, we need to convert string X into an anagram of string Y with minimum replacements. If we have multiple ways of achieving the target, we go for the lexicographically smaller string where the length of each string \in [1, 100000]
Examples:
Input : X = "CDBABC"
Y = "ADCABD"
Output : Anagram : ADBADC
Number of changes made: 2
Input : X = "PJPOJOVMAK"
Y = "FVACRHLDAP"
Output : Anagram : ACPDFHVLAR
Number of changes made: 7
Approach used: We have to convert string X into a lexicographically smallest anagram of string Y doing minimum replacements in the original string X. We maintain two counter arrays that store the count/frequency of each character in the two strings. Let counters of the two strings be Count_{x} and Count_{y} . Now, anagrams by definition mean that the frequency of the characters in two anagrams is always equal. Thus, to convert string X into an anagram of string Y, the frequency of characters should be equal. Therefore, the total number of alteration we need to make in total to convert string X into an anagram of string Y is (\sum |Count_{x_{i}} - Count_{y_{i}}|)/2 , where we iterate for each character i.
Half the job is done as we know how many replacements are to be done. We now need the lexicographically smaller string. Now, for a specific position, we look for all possible characters from 'A' to 'Z' and check for each character whether it could be fit in this position or now. For a better understanding, we iterate for each position in the string. Check if is there is a character that is there in string Y and not in string X (or the frequency of character is more in string Y and less in string X). Now, if there is one, we check that the character at the current position in X, is it unnecessary? i.e. does it have more frequency in string X and less frequency in string Y. Now, if all the boxes are ticked, we further check if we insert the character in this position, as we need to generate the lexicographically smaller string. If all the conditions are true, we replace the character in string X with the character in string Y. After all such replacements, we can print the altered string X as the output.
Implementation:
C++
// C++ program to convert string X to
// string Y which minimum number of changes.
#include <bits/stdc++.h>
using namespace std;
#define MAX 26
// Function that converts string X
// into lexicographically smallest
// anagram of string Y with minimal changes
void printAnagramAndChanges(string X, string Y)
{
int countx[MAX] = {0}, county[MAX] = {0},
ctrx[MAX] = {0}, ctry[MAX] = {0};
int change = 0;
int l = X.length();
// Counting frequency of characters
// in each string.
for (int i = 0; i < l; i++) {
countx[X[i] - 'A']++;
county[Y[i] - 'A']++;
}
// We maintain two more counter arrays
// ctrx[] and ctry[]
// Ctrx[] maintains the count of extra
// elements present in string X than
// string Y
// Ctry[] maintains the count of
// characters missing from string X
// which should be present in string Y.
for (int i = 0; i < MAX; i++) {
if (countx[i] > county[i])
ctrx[i] += (countx[i] - county[i]);
else if (countx[i] < county[i])
ctry[i] += (county[i] - countx[i]);
change += abs(county[i] - countx[i]);
}
for (int i = 0; i < l; i++) {
// This means that we cannot edit the
// current character as it's frequency
// in string X is equal to or less
// than the frequency in string Y.
// Thus, we go to the next position
if (ctrx[X[i] - 'A'] == 0)
continue;
// Here, we try to find that character,
// which has more frequency in string Y
// and less in string X. We try to find
// this character in lexicographical
// order so that we get
// lexicographically smaller string
int j;
for (j = 0; j < MAX; j++)
if ((ctry[j]) > 0)
break;
// This portion deals with the
// lexicographical property.
// Now, we put a character in string X
// when either this character has smaller
// value than the character present there
// right now or if this is the last position
// for it to exchange, else we fix the
// character already present here in
// this position.
if (countx[X[i] - 'A'] == ctrx[X[i] - 'A']
|| X[i] - 'A' > j) {
countx[X[i] - 'A']--;
ctrx[X[i] - 'A']--;
ctry[j]--;
X[i] = 'A' + j;
}
else
countx[X[i] - 'A']--;
}
cout << "Anagram : " << X << endl;
cout << "Number of changes made : " << change / 2;
}
// Driver program
int main()
{
string x = "CDBABC", y = "ADCABD";
printAnagramAndChanges(x, y);
return 0;
}
Java
// Java program to convert string X to
// string Y which minimum number of changes.
class GFG
{
static final int MAX = 26;
// Function that converts string X
// into lexicographically smallest
// anagram of string Y with minimal changes
static void printAnagramAndChanges(char[] X,
char[] Y)
{
int countx[] = new int[MAX], county[] = new int[MAX],
ctrx[] = new int[MAX], ctry[] = new int[MAX];
int change = 0;
int l = X.length;
// Counting frequency of characters
// in each string.
for (int i = 0; i < l; i++)
{
countx[X[i] - 'A']++;
county[Y[i] - 'A']++;
}
// We maintain two more counter arrays
// ctrx[] and ctry[]
// Ctrx[] maintains the count of extra
// elements present in string X than
// string Y
// Ctry[] maintains the count of
// characters missing from string X
// which should be present in string Y.
for (int i = 0; i < MAX; i++)
{
if (countx[i] > county[i])
{
ctrx[i] += (countx[i] - county[i]);
}
else if (countx[i] < county[i])
{
ctry[i] += (county[i] - countx[i]);
}
change += Math.abs(county[i] - countx[i]);
}
for (int i = 0; i < l; i++)
{
// This means that we cannot edit the
// current character as it's frequency
// in string X is equal to or less
// than the frequency in string Y.
// Thus, we go to the next position
if (ctrx[X[i] - 'A'] == 0)
{
continue;
}
// Here, we try to find that character,
// which has more frequency in string Y
// and less in string X. We try to find
// this character in lexicographical
// order so that we get
// lexicographically smaller string
int j;
for (j = 0; j < MAX; j++)
{
if ((ctry[j]) > 0)
{
break;
}
}
// This portion deals with the
// lexicographical property.
// Now, we put a character in string X
// when either this character has smaller
// value than the character present there
// right now or if this is the last position
// for it to exchange, else we fix the
// character already present here in
// this position.
if (countx[X[i] - 'A'] == ctrx[X[i] - 'A']
|| X[i] - 'A' > j)
{
countx[X[i] - 'A']--;
ctrx[X[i] - 'A']--;
ctry[j]--;
X[i] = (char) ('A' + j);
}
else
{
countx[X[i] - 'A']--;
}
}
System.out.println("Anagram : " + String.valueOf(X));
System.out.println("Number of changes made : " + change / 2);
}
// Driver code
public static void main(String[] args)
{
String x = "CDBABC", y = "ADCABD";
printAnagramAndChanges(x.toCharArray(), y.toCharArray());
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program to convert string X to
# string Y which minimum number of changes.
MAX = 26
# Function that converts string X
# into lexicographically smallest
# anagram of string Y with minimal changes
def printAnagramAndChanges(x, y):
x = list(x)
y = list(y)
countx, county = [0] * MAX, [0] * MAX
ctrx, ctry = [0] * MAX, [0] * MAX
change = 0
l = len(x)
# Counting frequency of characters
# in each string.
for i in range(l):
countx[ord(x[i]) - ord('A')] += 1
county[ord(y[i]) - ord('A')] += 1
# We maintain two more counter arrays
# ctrx[] and ctry[]
# Ctrx[] maintains the count of extra
# elements present in string X than
# string Y
# Ctry[] maintains the count of
# characters missing from string X
# which should be present in string Y.
for i in range(MAX):
if countx[i] > county[i]:
ctrx[i] += (countx[i] - county[i])
elif countx[i] < county[i]:
ctry[i] += (county[i] - countx[i])
change += abs(county[i] - countx[i])
for i in range(l):
# This means that we cannot edit the
# current character as it's frequency
# in string X is equal to or less
# than the frequency in string Y.
# Thus, we go to the next position
if ctrx[ord(x[i]) - ord('A')] == 0:
continue
# Here, we try to find that character,
# which has more frequency in string Y
# and less in string X. We try to find
# this character in lexicographical
# order so that we get
# lexicographically smaller string
j = 0
for j in range(MAX):
if ctry[j] > 0:
break
# This portion deals with the
# lexicographical property.
# Now, we put a character in string X
# when either this character has smaller
# value than the character present there
# right now or if this is the last position
# for it to exchange, else we fix the
# character already present here in
# this position.
if countx[ord(x[i]) -
ord('A')] == ctrx[ord(x[i]) - ord('A')] or \
ord(x[i]) - ord('A') > j:
countx[ord(x[i]) - ord('A')] -= 1
ctrx[ord(x[i]) - ord('A')] -= 1
ctry[j] -= 1
x[i] = chr(ord('A') + j)
else:
countx[ord(x[i]) - ord('A')] -= 1
print("Anagram :", ''.join(x))
print("Number of changes made :", change // 2)
# Driver Code
if __name__ == "__main__":
x = "CDBABC"
y = "ADCABD"
printAnagramAndChanges(x, y)
# This code is contributed by
# sanjeev2552
C#
// C# program to convert string X to
// string Y which minimum number of changes.
using System;
class GFG
{
static readonly int MAX = 26;
// Function that converts string X
// into lexicographically smallest
// anagram of string Y with minimal changes
static void printAnagramAndChanges(char[] X,
char[] Y)
{
int []countx = new int[MAX];
int []county = new int[MAX];
int []ctrx = new int[MAX];
int []ctry = new int[MAX];
int change = 0;
int l = X.Length;
// Counting frequency of characters
// in each string.
for (int i = 0; i < l; i++)
{
countx[X[i] - 'A']++;
county[Y[i] - 'A']++;
}
// We maintain two more counter arrays
// ctrx[] and ctry[]
// Ctrx[] maintains the count of extra
// elements present in string X than
// string Y
// Ctry[] maintains the count of
// characters missing from string X
// which should be present in string Y.
for (int i = 0; i < MAX; i++)
{
if (countx[i] > county[i])
{
ctrx[i] += (countx[i] - county[i]);
}
else if (countx[i] < county[i])
{
ctry[i] += (county[i] - countx[i]);
}
change += Math.Abs(county[i] - countx[i]);
}
for (int i = 0; i < l; i++)
{
// This means that we cannot edit the
// current character as it's frequency
// in string X is equal to or less
// than the frequency in string Y.
// Thus, we go to the next position
if (ctrx[X[i] - 'A'] == 0)
{
continue;
}
// Here, we try to find that character,
// which has more frequency in string Y
// and less in string X. We try to find
// this character in lexicographical
// order so that we get
// lexicographically smaller string
int j;
for (j = 0; j < MAX; j++)
{
if ((ctry[j]) > 0)
{
break;
}
}
// This portion deals with the
// lexicographical property.
// Now, we put a character in string X
// when either this character has smaller
// value than the character present there
// right now or if this is the last position
// for it to exchange, else we fix the
// character already present here in
// this position.
if (countx[X[i] - 'A'] == ctrx[X[i] - 'A']
|| X[i] - 'A' > j)
{
countx[X[i] - 'A']--;
ctrx[X[i] - 'A']--;
ctry[j]--;
X[i] = (char) ('A' + j);
}
else
{
countx[X[i] - 'A']--;
}
}
Console.WriteLine("Anagram : " +
String.Join("",X));
Console.WriteLine("Number of changes made : " +
change / 2);
}
// Driver code
public static void Main(String[] args)
{
String x = "CDBABC", y = "ADCABD";
printAnagramAndChanges(x.ToCharArray(),
y.ToCharArray());
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to convert string X to
// string Y which minimum number of changes.
const MAX = 26;
// Function that converts string X
// into lexicographically smallest
// anagram of string Y with minimal changes
function printAnagramAndChanges(X, Y)
{
var countx = new Array(MAX).fill(0);
var county = new Array(MAX).fill(0);
var ctrx = new Array(MAX).fill(0);
var ctry = new Array(MAX).fill(0);
var change = 0;
var l = X.length;
// Counting frequency of characters
// in each string.
for (var i = 0; i < l; i++) {
countx[X[i].charCodeAt(0) - "A".charCodeAt(0)]++;
county[Y[i].charCodeAt(0) - "A".charCodeAt(0)]++;
}
// We maintain two more counter arrays
// ctrx[] and ctry[]
// Ctrx[] maintains the count of extra
// elements present in string X than
// string Y
// Ctry[] maintains the count of
// characters missing from string X
// which should be present in string Y.
for (var i = 0; i < MAX; i++) {
if (countx[i] > county[i]) {
ctrx[i] += countx[i] - county[i];
} else if (countx[i] < county[i]) {
ctry[i] += county[i] - countx[i];
}
change += Math.abs(county[i] - countx[i]);
}
for (var i = 0; i < l; i++) {
// This means that we cannot edit the
// current character as it's frequency
// in string X is equal to or less
// than the frequency in string Y.
// Thus, we go to the next position
if (ctrx[X[i].charCodeAt(0) -
"A".charCodeAt(0)] === 0)
{
continue;
}
// Here, we try to find that character,
// which has more frequency in string Y
// and less in string X. We try to find
// this character in lexicographical
// order so that we get
// lexicographically smaller string
var j;
for (j = 0; j < MAX; j++) {
if (ctry[j] > 0) {
break;
}
}
// This portion deals with the
// lexicographical property.
// Now, we put a character in string X
// when either this character has smaller
// value than the character present there
// right now or if this is the last position
// for it to exchange, else we fix the
// character already present here in
// this position.
if (
countx[X[i].charCodeAt(0) - "A".charCodeAt(0)] ===
ctrx[X[i].charCodeAt(0) - "A".charCodeAt(0)] ||
X[i].charCodeAt(0) - "A".charCodeAt(0) > j
) {
countx[X[i].charCodeAt(0) - "A".charCodeAt(0)]--;
ctrx[X[i].charCodeAt(0) - "A".charCodeAt(0)]--;
ctry[j]--;
X[i] = String.fromCharCode("A".charCodeAt(0) + j);
} else {
countx[X[i].charCodeAt(0) - "A".charCodeAt(0)]--;
}
}
document.write("Anagram : " + X.join("") + "<br>");
document.write("Number of changes made : " + change / 2);
}
// Driver code
var x = "CDBABC",
y = "ADCABD";
printAnagramAndChanges(x.split(""), y.split(""));
</script>
OutputAnagram : ADBADC
Number of changes made : 2
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string.
Auxiliary Space: O(4*26), as we are using extra space.
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