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$
sconsists 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
iin 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
ansby 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++)
π§βπ» Code (Java)
π Code (Python)
π§ 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