Names Requiring Minimum Changes to Become an Anagram
You are given a string name and a list of strings nameList. Return every string from nameList that requires the minimum number of character changes to become an anagram of name.
Character Change
- In one change, any character in a candidate string may be replaced with any other character.
- Characters may be rearranged freely after the changes because only the resulting character frequencies matter.
- For each character, count how many additional occurrences are needed to match
name. The sum of these deficits is the minimum number of changes.
- Character comparisons are case-sensitive.
- Every candidate string has the same length as
name.
Result Rules
- Compute the minimum number of character changes required for each string in
nameList.
- Return all strings whose required number of changes is the smallest among all candidates.
- Return matching strings in the same order in which they appear in
nameList.
- If the same matching string appears multiple times, preserve all of its occurrences.
Method
Find Names Requiring Minimum Changes
List
findNamesWithMinimumChanges(String name, List
nameList)
name is the target string whose character frequencies must be matched.
nameList contains the candidate strings.
- Return all candidates requiring the globally minimum number of character replacements.
Constraints
1 ≤ name.length() ≤ 100,000
1 ≤ nameList.size() ≤ 100,000
candidate.length() == name.length() for every candidate in nameList
- The total number of characters across all strings in
nameList does not exceed 1,000,000.
name and every candidate contain only uppercase and lowercase English letters (A-Z and a-z).
name, nameList, and the strings inside nameList are never null.
Examples
Example 1
findNamesWithMinimumChanges(name = "aabb", nameList = List.of("abca", "bbaa", "ccab"))
Output: List.of("bbaa")
The string "bbaa" is already an anagram of "aabb", so it requires zero changes. The other candidates require at least one change.
Example 2
findNamesWithMinimumChanges(name = "listen", nameList = List.of("silent", "listed", "enlist", "little"))
Output: List.of("silent", "enlist")
Both "silent" and "enlist" are already anagrams of "listen". They are returned in their original input order.
Example 3
findNamesWithMinimumChanges(name = "aabc", nameList = List.of("aabb", "abcc", "dddd", "aabb"))
Output: List.of("aabb", "abcc", "aabb")
Each returned string requires exactly one character change. The duplicate occurrence of "aabb" is preserved.
Example 4
findNamesWithMinimumChanges(name = "Abc", nameList = List.of("abc", "cbA", "ABC"))
Output: List.of("cbA")
Character matching is case-sensitive. The string "cbA" already contains exactly the same characters as "Abc".