10(March) Remove all duplicates from a given string
10. Remove Duplicate Characters
The problem statement can be found at the following link: Question Link
My Approach
Initialization:
Initialize an empty unordered set
seen
to store characters that have been encountered.Initialize an empty string
result
to store the final output.
Iteration Process:
Iterate through each character
c
in the input stringstr
.
Check for Duplicates:
For each character
c
, check if it has been seen before. If not, append it to theresult
string and add it to theseen
set.
Finalization:
After iterating through all characters in the input string, return the
result
string containing unique characters only.
This approach effectively removes duplicate characters from the input string while maintaining the original order of characters.
Time and Auxiliary Space Complexity
Time Complexity: O(N), where N is the length of the input string.
Auxiliary Space Complexity: O(N), where N is the length of the input string, for storing unique characters in the unordered set.
Code (C++)
class Solution {
public:
std::string removeDuplicates(std::string str) {
std::unordered_set<char> seen;
std::string result = "";
for (char& c : str) {
if (seen.find(c) == seen.end()) {
result += c;
seen.insert(c);
}
}
return result;
}
};
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