The Wayback Machine - https://web.archive.org/web/20211228093124/https://www.geeksforgeeks.org/count-of-distinct-strings-that-can-be-obtained-after-performing-exactly-one-swap/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 27 Dec, 2021

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: 6
Explanation: Following are the strings formed by doing exactly one swap
strings = [“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++




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to count number of distinct
// string formed after one swap
long 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 Code
int main()
{
    string S = "geek";
  
    // Function Call
    long long ans = countStrings(S);
    cout << ans << endl;
  
    return 0;
}
Output
6

Time complexity: O(N)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!