General GFG Question

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.

In one swap, Geek can pick two distinct indexes i and j (i.e 1 < i < j < |S| ) of the string, then swap the characters at the position i and j.

S = “geek”
Output: 6
Explanation: After one swap, there are only 6 distinct strings possible. (i.e “egek”,“eegk”,“geek”,“geke”,“gkee” and “keeg”)`

I have made the solution using 2 for loops and a HashSet. I am thinking that is there any more optimized way to solve this problem?

int freq[26];
for(int i=0;i<26;i++)freq[i]=0;

long long ans=1;//original string
freq[s[0]-‘a’]++;
for(int i=1;i<s.length();i++)
{
ans+=(i-freq[s[i]-‘a’]);
freq[s[i]-‘a’]++;
}
return ans;

Can you please suggest something on printing these strings too.

The number of strings would be large enough.I dont think it is possible to print them.