10. Exactly One Swap
β GFG solution to the Exactly One Swap problem: count distinct strings after one swap. Uses hashing & counting. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given a string s, return the number of distinct strings that can be obtained by exactly one swap of two different indices (i < j)
.
π Examples
Example 1
Input: s = "geek"
Output: 6
Explanation: After one swap, there are 6 distinct strings possible:
"egek", "eegk", "geek", "geke", "gkee", and "keeg".
Example 2
Input: s = "aaaa"
Output: 1
Explanation: Only one distinct string is possible after any swap ("aaaa").
π Constraints
$2 β€ s.size() β€ 10^4$
s
consists of lowercase English letters.
β
My Approach
π‘ Idea
Maintain a frequency array
m[26]
to track how many times each lowercase character has appeared.For each character at index
i
in the string:Add
i - m[s[i] - 'a']
to the result, which effectively counts how many earlier characters are not equal to the current character.Increment the frequency of
s[i]
.
After the loop, check if any character appears more than once:
If so, increment the result once more to reflect the presence of a duplicate.
βοΈ Algorithm Steps:
Initialize
vector<int> m(26)
to store character counts.Initialize
ans = 0
.Loop through the string:
For each character
s[i]
, addi - m[s[i]-'a']
toans
.Increment
m[s[i]-'a']
by 1.
After the loop, scan the frequency array:
If any value > 1, increment
ans
by 1 and break.
Return
ans
.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we iterate through the string once while maintaining a constant-size frequency array.
Expected Auxiliary Space Complexity: O(1), as we only use an array of fixed size 26.
π§βπ» Code (C++)
class Solution{
public:
int countStrings(string &s){
vector<int> m(26);
int ans = 0;
for(int i = 0; i < s.size(); ++i){
ans += i - m[s[i] - 'a'];
++m[s[i] - 'a'];
}
for(int x : m) if(x > 1){ ++ans; break; }
return ans;
}
};
π§βπ» Code (Java)
class Solution {
public int countStrings(String s) {
int[] m = new int[26];
int ans = 0;
for (int i = 0; i < s.length(); ++i) {
ans += i - m[s.charAt(i) - 'a'];
++m[s.charAt(i) - 'a'];
}
for (int x : m) if (x > 1) { ans++; break; }
return ans;
}
}
π Code (Python)
class Solution:
def countStrings(self, s):
m = [0]*26
ans = 0
for i, ch in enumerate(s):
ans += i - m[ord(ch) - 97]
m[ord(ch) - 97] += 1
if any(x > 1 for x in m):
ans += 1
return ans
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated