Character Removal Anagram Matching
StringsAuto-graded · 25 test casesLast updated
Tests string manipulation and character frequency analysis to determine if two strings can become anagrams through optional single-character removal.
You are given a list of test cases. Each test case consists of two lowercase strings.
For each pair of strings, determine whether they can be made into anagrams using the following operations:
- From the first string, you may optionally remove all occurrences of exactly one character
- From the second string, you may optionally remove all occurrences of exactly one character
- You can also choose to remove nothing from either or both strings
Two strings are anagrams if they contain exactly the same characters with exactly the same frequencies (i.e., identical character multisets).
Return a list of boolean values, one for each test case, indicating whether the transformation is possible.
Constraints
- 1 ≤ number of test cases ≤ 100
- 1 ≤ length of each string ≤ 1000
- All strings contain only lowercase English letters
Examples
Example 1
Input: can_match_anagrams([['safddadfs', 'famafmss']])
Output: [True]
Example 2
Input: can_match_anagrams([['abc', 'abc'], ['aabb', 'ab'], ['abc', 'def'], ['aab', 'abb']])
Output: [True, False, False, False]
Hints
Hint 1
Count character frequencies in both strings and identify which characters have mismatched counts.
Hint 2
If there are no mismatches, the strings are already anagrams. If there is exactly one mismatched character, removing it from both strings makes them match.
Hint 3
If there are exactly two mismatched characters, check whether one appears only in the first string and the other appears only in the second string.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to count character frequencies in both strings and analyze which characters have different counts.
Build frequency maps for both strings and identify the set of characters whose counts differ between them. Call this set of mismatched characters D.
Since removing a character only affects that specific character's frequency, every character not involved in a removal must already have matching frequencies. This means D must be a subset of the characters we choose to remove.
Case analysis:
-
No mismatches (
|D| = 0): The strings are already anagrams. Return true. -
One mismatch (
|D| = 1): Only one character has differing counts. Remove this character from both strings, which sets both frequencies to zero. Return true. -
Two mismatches (
|D| = 2): Call the mismatched charactersxandy. We need to fix both differences with our two removal operations. Removing the same character from both strings only fixes one mismatch, so we must remove different characters:xfrom one string andyfrom the other. After removal,xwill have frequency 0 in one string, so it must already be 0 in the other string (meaningxappears exclusively in one string). The same logic applies toy. Return true if and only if one character appears exclusively in the first string and the other exclusively in the second string. -
Three or more mismatches (
|D| ≥ 3): We can only perform two removal operations, which cannot fix three or more mismatches. Return false.
Why it works
The case analysis exhaustively covers all possible removal choices. Characters outside the removal set must maintain their original frequencies, so they cannot be in D. Characters that are removed end up with frequency 0, which constrains what the other string must contain.
For the example "safddadfs" and "famafmss":
- First string has: {s:2, a:2, f:2, d:3}
- Second string has: {f:2, a:2, m:2, s:2}
- Mismatched characters: {d, m}
- Character 'd' appears only in the first string, 'm' appears only in the second
- Removing all 'd' from the first and all 'm' from the second gives {s:2, a:2, f:2} in both
- Result: true
Complexity
Time: O(n × m) per test case in the worst case, where n and m are the string lengths. The brute-force solution tries at most 27 × 27 removal combinations (including no removal), and each check compares frequency maps in O(26) time. The optimized case-analysis approach runs in O(n + m) per test case.
Space: O(1) extra space beyond the input, since we only store frequency counts for at most 26 letters.
from collections import Counter
from typing import List
def can_match_anagrams(test_cases: List[List[str]]) -> List[bool]:
results = []
for password1, password2 in test_cases:
count1 = Counter(password1)
count2 = Counter(password2)
choices1 = [None] + list(count1)
choices2 = [None] + list(count2)
similar = False
for char1 in choices1:
remaining1 = count1.copy()
if char1 is not None:
del remaining1[char1]
for char2 in choices2:
remaining2 = count2.copy()
if char2 is not None:
del remaining2[char2]
if remaining1 == remaining2:
similar = True
break
if similar:
break
results.append(similar)
return results