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
seento store characters that have been encountered.Initialize an empty string
resultto store the final output.
Iteration Process:
Iterate through each character
cin the input stringstr.
Check for Duplicates:
For each character
c, check if it has been seen before. If not, append it to theresultstring and add it to theseenset.
Finalization:
After iterating through all characters in the input string, return the
resultstring 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