Count of distinct permutation of a String obtained by swapping only unequal characters
Last Updated :
12 Nov, 2023
Given a string find the number of unique permutations that can be obtained by swapping two indices such that the elements at these indices are distinct.
NOTE: Swapping is always performed in the original string.
Examples:
Input: str = “sstt”
Output: 5
Explanation:
Swap str[0] with str[2], string obtained “tsst” which is valid (str[0]!=str[2])
Swap str[0] with str[3]. string obtained “tsts”
Swap str[1] with str[2], string obtained “stst”
Swap str[1] with str[3], string obtained “stts”
Hence total 5 strings can be obtained including the given string (“sstt”)
Input: str = “abcd”
Output: 7
Naive Approach:
- Create a set to store unique strings
- Loop through each pair of indices in the given string
- Check if the elements at the pair of indices are distinct
- If the elements are distinct, swap the elements at those indices and add the resulting string to the set
- Swap the elements back to their original positions
- Add 1 to count the original string
- Return the number of unique permutations, including the original string.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <set>
#include <string>
using namespace std;
int countUniquePermutations(string str)
{
set<string> uniqueStrings;
for ( int i = 0; i < str.length(); i++) {
for ( int j = i + 1; j < str.length(); j++) {
if (str[i] != str[j]) {
swap(str[i], str[j]);
uniqueStrings.insert(str);
swap(str[i], str[j]);
}
}
}
return uniqueStrings.size() + 1;
}
int main()
{
string str = "sstt" ;
cout << countUniquePermutations(str);
return 0;
}
|
Java
import java.util.HashSet;
import java.util.Set;
public class UniquePermutations {
public static int countUniquePermutations(String str)
{
Set<String> uniqueStrings = new HashSet<>();
for ( int i = 0 ; i < str.length(); i++) {
for ( int j = i + 1 ; j < str.length(); j++) {
if (str.charAt(i) != str.charAt(j)) {
char [] strArray = str.toCharArray();
char temp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = temp;
String swappedStr
= new String(strArray);
uniqueStrings.add(swappedStr);
temp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = temp;
}
}
}
return uniqueStrings.size() + 1 ;
}
public static void main(String[] args)
{
String str = "sstt" ;
System.out.println(countUniquePermutations(str));
}
}
|
Python3
def count_unique_permutations(s):
unique_strings = set ()
for i in range ( len (s)):
for j in range (i + 1 , len (s)):
if s[i] ! = s[j]:
s_list = list (s)
s_list[i], s_list[j] = s_list[j], s_list[i]
unique_strings.add("".join(s_list))
return len (unique_strings) + 1
if __name__ = = "__main__" :
input_str = "sstt"
print (count_unique_permutations(input_str))
|
C#
using System;
using System.Collections.Generic;
class Program
{
static int CountUniquePermutations( string str)
{
HashSet< string > uniqueStrings = new HashSet< string >();
for ( int i = 0; i < str.Length; i++)
{
for ( int j = i + 1; j < str.Length; j++)
{
if (str[i] != str[j])
{
char [] chars = str.ToCharArray();
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
string newString = new string (chars);
uniqueStrings.Add(newString);
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
}
return uniqueStrings.Count + 1;
}
static void Main()
{
string str = "sstt" ;
Console.WriteLine(CountUniquePermutations(str));
}
}
|
Javascript
function countUniquePermutations(str) {
let uniqueStrings = new Set();
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j < str.length; j++) {
if (str[i] !== str[j]) {
let strArray = str.split( '' );
[strArray[i], strArray[j]] = [strArray[j], strArray[i]];
let modifiedStr = strArray.join( '' );
uniqueStrings.add(modifiedStr);
[strArray[i], strArray[j]] = [strArray[j], strArray[i]];
}
}
}
return uniqueStrings.size + 1;
}
let str = "sstt" ;
console.log(countUniquePermutations(str));
|
Time Complexity: The time complexity of this algorithm is O(n2 * log n), where n is the length of the input string. This is because we have two nested loops, and within each loop, we perform a constant-time set insertion operation, which has a time complexity of O(log n) on average. Therefore, the overall time complexity is O(n^2 * log n).
Auxiliary Space: The space complexity of this algorithm is also O(n2). This is because we create a set to store the unique strings, and the size of the set can be as large as n^2 in the worst case, if all possible string permutations are unique. Additionally, we store the input string itself, which has a size of n. Therefore, the overall space complexity is O(n^2 + n), which simplifies to O(n^2).
Efficient Approach: The problem can be solved using HashMap by the following steps:
- Create a hashmap and store the frequency of every character of the given string.
- Create a variable count, to store the total number of characters in the given string, i.e. count=str.length() and a variable ans to store the number of unique permutations possible and initialize ans=0.
- Traverse the string and for each character:
- Find the number of different characters present in the right of the current index. This can be done by subtracting the frequency of that character by the total count.
- Now add this calculated value to ans, as this is the number of characters with which the current character can be swapped to create a unique permutation.
- Now, Reduce the frequency of the current character and count by 1, so that it cannot interfere with the calculations of the same elements present to the right of it.
- Return ans+1, because the given string is also a unique permutation.
C++
#include <bits/stdc++.h>
using namespace std;
int validPermutations(string str)
{
unordered_map< char , int > m;
int count = str.length(), ans = 0;
for ( int i = 0; i < str.length(); i++) {
m[str[i]]++;
}
for ( int i = 0; i < str.length(); i++) {
ans += count - m[str[i]];
m[str[i]]--;
count--;
}
return ans + 1;
}
int main()
{
string str = "sstt" ;
cout << validPermutations(str);
return 0;
}
|
Java
import java.util.HashMap;
class GFG {
static int validPermutations(String str)
{
HashMap<Character, Integer> m
= new HashMap<Character, Integer>();
int count = str.length(), ans = 0 ;
for ( int i = 0 ; i < str.length(); i++) {
m.put(str.charAt(i),
m.getOrDefault(str.charAt(i), 0 ) + 1 );
}
for ( int i = 0 ; i < str.length(); i++) {
ans += count - m.get(str.charAt(i));
m.put(str.charAt(i), m.get(str.charAt(i)) - 1 );
count--;
}
return ans + 1 ;
}
public static void main(String[] args)
{
String str = "sstt" ;
System.out.println(validPermutations(str));
}
}
|
Python3
def validPermutations( str ):
m = {}
count = len ( str )
ans = 0
for i in range ( len ( str )):
if ( str [i] in m):
m[ str [i]] + = 1
else :
m[ str [i]] = 1
for i in range ( len ( str )):
ans + = count - m[ str [i]]
m[ str [i]] - = 1
count - = 1
return ans + 1
if __name__ = = '__main__' :
str = "sstt"
print (validPermutations( str ))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static int validPermutations(String str)
{
Dictionary< char , int > m
= new Dictionary< char , int >();
int count = str.Length, ans = 0;
for ( int i = 0; i < str.Length; i++) {
if (m.ContainsKey(str[i]))
m[str[i]]=m[str[i]]+1;
else
m.Add(str[i], 1);
}
for ( int i = 0; i < str.Length; i++) {
ans += count - m[str[i]];
if (m.ContainsKey(str[i]))
m[str[i]]=m[str[i]]-1;
count--;
}
return ans + 1;
}
public static void Main(String[] args)
{
String str = "sstt" ;
Console.WriteLine(validPermutations(str));
}
}
|
Javascript
<script>
function validPermutations(str) {
let m = new Map();
let count = str.length,
ans = 0;
for (let i = 0; i < str.length; i++) {
if (m.has(str[i])) {
m.set(str[i], m.get(str[i]) + 1);
} else {
m.set(str[i], 1);
}
}
for (let i = 0; i < str.length; i++)
{
ans += count - m.get(str[i]);
m.set(str[i], m.get(str[i]) - 1);
count--;
}
return ans + 1;
}
let str = "sstt" ;
document.write(validPermutations(str));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...