String Trimmer
String Trimmer – A Fundamental Filtering Problem
Problem Statement
You are given T
test cases. Each test case consists of two strings, A
and B
, comprised of lowercase English letters and separated by a space.
Your task is to remove from string A
all characters that are present in string B
. The resulting string should preserve the original order of characters in A
, excluding any characters that occur in B
.
Examples
Input
Output
Explanation
-
In the first case, we remove all characters from
"data structures"
that appear in"smart"
, resulting in"srucures"
. -
In the second case, we remove characters from
"interviews"
that appear in"smart"
, resulting in"ineview"
.
Best Data Structure for the Job
To determine membership of a character in B
efficiently, a HashSet is ideal. It provides constant-time average lookup and allows us to quickly verify whether each character in A
should be excluded
Different Approaches
Approach 1: Brute Force Character Check
Iterate through each character in A
and, for each character, check if it exists in B
using a nested loop.
Approach 2: Frequency Array
Use a boolean array of size 26 to mark the presence of characters in B
.
Approach 3: HashSet Lookup
Use a HashSet<Character>
to store characters in B
, then filter A
.
⚠️Common Mistakes and Pitfalls
-
Failing to preserve the order of characters in
A
after filtering. -
Assuming inputs might contain uppercase characters or spaces—if constraints don’t include them, avoid overgeneralizing.
-
Using nested loops unnecessarily, which may lead to timeouts on larger inputs.
📊 Time and Space Complexity Comparison
Approach | Time Complexity | Space Complexity |
---|---|---|
Brute Force | O(n * m) | O(1) |
Frequency Array | O(n + m) | O(1) |
HashSet Lookup | O(n + m) | O(m) |
🌍Real-world Applications
-
Building email or comment filters that block blacklisted words or characters.
-
Designing input sanitizers for user-generated content.
-
Lightweight text preprocessing in NLP tasks where stopword or keyword removal is necessary.
I hope you found this article insightful! Keep exploring, keep learning, and don’t forget to check back daily for more exciting problem breakdowns. If you know someone who would benefit from this, share it with them and help them grow too! That’s it for today—see you in the next post!
Signing off!!
Master DSA One Problem at a Time :)
Comments
Post a Comment