Count of distinct strings that can be obtained after performing exactly one swap - GeeksforGeeks

10 Jan, 2022
Given a string s containing lowercase English alphabet characters. The task is to calculate the number of distinct strings that can be obtained after performing exactly one swap.
Input: s = “geek”Output: 6Explanation: Following are the strings formed by doing exactly one swapstrings = [“egek”,”eegk”,”geek”,”geke”,”gkee”, “keeg”]Therefore, there are 6 distinct possible strings.
Input: s = “ab”Output: 1
Approach: This problem can be solved by using HashMaps. Follow the steps below to solve the given problem.
Check for the number of unique elements in the string s.
Store the frequencies of all the unique characters in a map.
Declare a variable say ans = 0, to store the number of distinct possible strings.
Iterate over the string and increment ans by no of elements apart from the current element which will be used to construct a new string.
Iterate over the string again and check if the frequency of some characters is greater than 2. If so then increment answer by 1 as they will be forming only one extra unique string.
Return ans as the final answer.
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to count number of distinct// string formed after one swaplong long countStrings(string S){    long long N = S.size();     // mp[] to store the frequency    // of each character    int mp[26] = { 0 };     // For storing frequencies    for (auto i : S) {        mp[i - 'a']++;    }    long long ans = 0;    for (auto i : S) {        ans += N - mp[i - 'a'];    }    ans /= 2;     for (int i = 0; i < 26; i++) {        if (mp[i] >= 2) {            ans++;            break;        }    }    return ans;} // Driver Codeint main(){    string S = "geek";     // Function Call    long long ans = countStrings(S);    cout << ans << endl;     return 0;}
// Java code to implement the above approachimport java.util.*;public class GFG{   // Function to count number of distinct// string formed after one swapstatic long countStrings(String S){    long N = S.length();     // mp[] to store the frequency    // of each character    int mp[] = new int[26];    for(int i = 0; i < 26; i++) {        mp[i] = 0;    }     // For storing frequencies    for (int i = 0; i < S.length(); i++) {        mp[S.charAt(i) - 'a']++;    }    long ans = 0;    for (int i = 0; i < S.length(); i++) {        ans += N - mp[S.charAt(i) - 'a'];    }    ans /= 2;     for (int i = 0; i < 26; i++) {        if (mp[i] >= 2) {            ans++;            break;        }    }    return ans;} // Driver codepublic static void main(String args[]){    String S = "geek";     // Function Call    long ans = countStrings(S);    System.out.println(ans);}} // This code is contributed by Samim Hossain Mondal.
# Python code to implement the above approach # Function to count number of distinct# string formed after one swapdef countStrings(S):    N = len(S);     # mp to store the frequency    # of each character    mp = [0 for i in range(26)];    for i in range(26):        mp[i] = 0;     # For storing frequencies    for i in range(N):        mp[ord(S[i]) - ord('a')] += 1;     ans = 0;    for i in range(N):        ans += N - mp[ord(S[i]) - ord('a')];     ans //= 2;     for i in range(26):        if (mp[i] >= 2):            ans += 1;            break;     return ans; # Driver codeif __name__ == '__main__':    S = "geek";     # Function Call    ans = countStrings(S);    print(ans); # This code is contributed by 29AjayKumar
// C# code to implement the above approachusing System;class GFG{   // Function to count number of distinct// string formed after one swapstatic long countStrings(string S){    long N = S.Length;     // mp[] to store the frequency    // of each character    int []mp = new int[26];    for(int i = 0; i < 26; i++) {        mp[i] = 0;    }     // For storing frequencies    for (int i = 0; i < S.Length; i++) {        mp[S[i] - 'a']++;    }    long ans = 0;    for (int i = 0; i < S.Length; i++) {        ans += N - mp[S[i] - 'a'];    }    ans /= 2;     for (int i = 0; i < 26; i++) {        if (mp[i] >= 2) {            ans++;            break;        }    }    return ans;} // Driver codepublic static void Main(){    string S = "geek";     // Function Call    long ans = countStrings(S);    Console.Write(ans);}} // This code is contributed by Samim Hossain Mondal.
<script> // JavaScript program for above approach // Function to count number of distinct// string formed after one swapfunction countStrings(S){    let N = S.length;     // mp[] to store the frequency    // of each character    let mp = new Map();     // For storing frequencies    for(let i = 0; i < S.length; i++)    {        if (!mp.has(S[i].charCodeAt(0) - 'a'.charCodeAt(0)))        {            mp.set(S[i].charCodeAt(0) - 'a'.charCodeAt(0), 1);        }        else        {            mp.set(S[i].charCodeAt(0) -                    'a'.charCodeAt(0),                   mp.get(S[i].charCodeAt(0) -                           'a'.charCodeAt(0)) + 1)        }    }    let ans = 0;    for(let i = 0; i < S.length; i++)    {        ans += N - mp.get(S[i].charCodeAt(0) -                           'a'.charCodeAt(0));    }    ans = Math.floor(ans / 2)     for(let i = 0; i < 26; i++)    {        if (mp.get(i) >= 2)        {            ans++;            break;        }    }    return ans;} // Driver Codelet S = "geek"; // Function Calllet ans = countStrings(S);document.write(ans + '<br>') // This code is contributed by Potta Lokesh </script>
6
Time complexity: O(N)Auxiliary Space: O(1)
 
lokeshpotta20
samim2000
29AjayKumar
Algo-Geek 2021
Swap-Program
Algo Geek
Arrays
Strings
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Sort strings on the basis of their numeric part
Divide given number into two even parts
Smallest set of vertices to visit all nodes of the given Graph
Count of Palindrome Strings in given Array of strings
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation