Check if characters of one string can be swapped to form other
Last Updated :
07 Oct, 2022
Two strings are given, we need to find whether we can form second string by swapping the character of the first string.
Examples:
Input : str1 = "geeksforgeeks"
str2 = "geegeeksksfor"
Output : YES
Input : str1 = "geeksfor"
str2 = "geeekfor"
Output : NO
First of all, we will find the length of strings and if lengths are not equal that means we can not form the target string by swapping characters of the first string. If lengths are equal then we iterate through the first string and create a map for it and after that, we will iterate through the second string and decrease the count of the map if any of the indexes go negative in the map that means we can not form the target string otherwise we can form the target string.
Algorithm:
1- l1 = str1.length() && l2 = str2.length()
2- if (l1 != l2)
print "NO"
3- Else
map[26] = {0};
for i=0 to l1
map[str1[i]-'a']++;
for i=0 to l2
map[str2[i]-'a']--;
if (map[str[2]-'a'<0)
print "NO"
4- if no index goes negative print "YES"
5- End
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX = 26;
bool targetstring(string str1, string str2)
{
int l1 = str1.length();
int l2 = str2.length();
// if length is not same print no
if (l1 != l2)
return false;
int map[MAX] = { 0 };
// Count frequencies of character in
// first string.
for (int i = 0; i < l1; i++)
map[str1[i] - 'a']++;
// iterate through the second string
// decrement counts of characters in
// second string
for (int i = 0; i < l2; i++) {
map[str2[i] - 'a']--;
// Since lengths are same, some
// value would definitely become
// negative if result is false.
if (map[str2[i] - 'a'] < 0)
return false;
}
return true;
}
// driver function
int main()
{
string str1 = "geeksforgeeks";
string str2 = "geegeeksksfor";
if (targetstring(str1, str2))
cout << "YES";
else
cout << "NO";
return 0;
}
Java
// Java program to check if
// characters of one string
// can be swapped to form other
class GFG
{
static int MAX = 26;
static boolean targetstring(String str1,
String str2)
{
int l1 = str1.length();
int l2 = str2.length();
// if length is not same print no
if (l1 != l2)
return false;
int []map = new int[MAX];
// Count frequencies of
// character in first string.
for (int i = 0; i < l1; i++)
map[str1.charAt(i) - 'a']++;
// iterate through the second
// string decrement counts of
// characters in second string
for (int i = 0; i < l2; i++)
{
map[str2.charAt(i) - 'a']--;
// Since lengths are same,
// some value would definitely
// become negative if result
// is false.
if (map[str2.charAt(i) - 'a'] < 0)
return false;
}
return true;
}
// Driver Code
public static void main(String args[])
{
String str1 = "geeksforgeeks";
String str2 = "geegeeksksfor";
if (targetstring(str1, str2))
System.out.print("YES");
else
System.out.print("NO");
}
}
// This code is contributed by
// Akanksha Rai
Python3
# Python3 program to check if
# characters of one string
# can be swapped to form other
MAX = 26
def targetstring(str1, str2):
l1 = len(str1)
l2 = len(str2)
# if length is not same print no
if (l1 != l2):
return False
map = [0] * MAX
# Count frequencies of character
# in first string.
for i in range (l1):
map[ord(str1[i]) - ord('a')] += 1
# iterate through the second string
# decrement counts of characters in
# second string
for i in range(l2) :
map[ord(str2[i]) - ord('a')] -= 1
# Since lengths are same, some
# value would definitely become
# negative if result is false.
if (map[ord(str2[i]) - ord('a')] < 0):
return False
return True
# Driver Code
if __name__ == "__main__":
str1 = "geeksforgeeks"
str2 = "geegeeksksfor"
if (targetstring(str1, str2)):
print("YES")
else:
print("NO")
# This code is contributed by ita_c
C#
// C# program to check if
// characters of one string
// can be swapped to form other
using System;
class GFG
{
static int MAX = 26;
static bool targetstring(string str1,
string str2)
{
int l1 = str1.Length;
int l2 = str2.Length;
// if length is not
// same print no
if (l1 != l2)
return false;
int []map = new int[MAX];
Array.Clear(map, 0, 26);
// Count frequencies of
// character in first string.
for (int i = 0; i < l1; i++)
map[str1[i] - 'a']++;
// iterate through the second
// string decrement counts of
// characters in second string
for (int i = 0; i < l2; i++)
{
map[str2[i] - 'a']--;
// Since lengths are same,
// some value would definitely
// become negative if result
// is false.
if (map[str2[i] - 'a'] < 0)
return false;
}
return true;
}
// Driver Code
static void Main()
{
string str1 = "geeksforgeeks";
string str2 = "geegeeksksfor";
if (targetstring(str1, str2))
Console.Write("YES");
else
Console.Write("NO");
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
<?php
// PHP program to check if
// characters of one string
// can be swapped to form other
$MAX = 26;
function targetstring($str1, $str2)
{
global $MAX;
$l1 = strlen($str1);
$l2 = strlen($str2);
// if length is not same print no
if ($l1 != $l2)
return false;
$map[$MAX] = array(0);
// Count frequencies of character
// in first string.
for ($i = 0; $i < $l1; $i++)
$map[$str1[$i] - 'a']++;
// iterate through the second string
// decrement counts of characters in
// second string
for ($i = 0; $i < $l2; $i++)
{
$map[$str2[$i] - 'a']--;
// Since lengths are same, some
// value would definitely become
// negative if result is false.
if ($map[$str2[$i] - 'a'] < 0)
return false;
}
return true;
}
// Driver Code
$str1 = "geeksforgeeks";
$str2 = "geegeeksksfor";
if (targetstring($str1, $str2))
echo "YES";
else
echo "NO";
// This code is contributed
// by Akanksha Rai
?>
JavaScript
<script>
// Javascript program to check if
// characters of one string
// can be swapped to form other
let MAX = 26;
function targetstring(str1,str2)
{
let l1 = str1.length;
let l2 = str2.length;
// if length is not same print no
if (l1 != l2)
return false;
let map = new Array(MAX);
for(let i = 0; i < map.length; i++)
{
map[i] = 0;
}
// Count frequencies of
// character in first string.
for (let i = 0; i < l1; i++)
map[str1[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
// iterate through the second
// string decrement counts of
// characters in second string
for (let i = 0; i < l2; i++)
{
map[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)]--;
// Since lengths are same,
// some value would definitely
// become negative if result
// is false.
if (map[str2[i] - 'a'.charCodeAt(0)] < 0)
return false;
}
return true;
}
// Driver Code
let str1 = "geeksforgeeks";
let str2 = "geegeeksksfor";
if (targetstring(str1, str2))
document.write("YES");
else
document.write("NO");
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Check if two strings can be made equal by swapping one character among each other Given two strings A and B of length N, the task is to check whether the two strings can be made equal by swapping any character of A with any other character of B only once.Examples: Input: A = "SEEKSFORGEEKS", B = "GEEKSFORGEEKG" Output: Yes "SEEKSFORGEEKS" and "GEEKSFORGEEKG" After removing the el
10 min read
Check whether second string can be formed from characters of first string Given two strings str1 and str2, check if str2 can be formed from str1 Example : Input : str1 = geekforgeeks, str2 = geeksOutput : YesHere, string2 can be formed from string1. Input : str1 = geekforgeeks, str2 = andOutput : NoHere string2 cannot be formed from string1. Input : str1 = geekforgeeks, s
5 min read
Check if string S can be converted to T by incrementing characters Given strings S and T. The task is to check if S can be converted to T by performing at most K operations. For the ith operation, select any character in S which has not been selected before, and increment the chosen character i times (i.e., replacing it with the letter i times ahead in the alphabet
8 min read
Check if two strings can be made equal by swapping pairs of adjacent characters Given two strings A and B of length N and M respectively and an array arr[] consisting of K integers, the task is to check if the string B can be obtained from the string A by swapping any pair of adjacent characters of the string A any number of times such that the swapped indices are not present i
15+ min read
Check if a string can be made equal to another string by swapping or replacement of characters Given two strings S1 and S2, the task is to check if string S1 can be made equal to string S2 by swapping any pair of characters replacing any character in the string S1. If it is possible to make the string S1 equal to S2, then print "Yes". Otherwise, print "No". Examples: Input: S1 = âabcâ, S2 = â
8 min read