Minimum Number of Steps to Make Two Strings Anagram
Real-world version: Restamps To Match The TrayThe statement here is our own: the same inputs, outputs and technique.
A ceramics studio keeps two trays with the same number of tiles. The trays arrive as strings target and tray of equal length, and each character is the lowercase letter stamped on one tile.
You may take any tile out of tray and restamp it with any lowercase letter you like. One restamp changes one tile, and a restamped tile stays in tray.
Return the fewest restamps that leave tray holding exactly the same tally of every letter as target. Where the tiles sit inside a tray never matters, only how many of each letter it holds.
Examples
Example 1
- Input
- target = "kite", tray = "kits"
- Output
- 1
Both trays hold one `k`, one `i` and one `t`. The `s` in `tray` has no counterpart, so restamping it as `e` gives the tallies of `target`.
Example 2
- Input
- target = "sunny", tray = "runny"
- Output
- 1
The `u`, both `n`s and the `y` already line up in tally. Restamping the `r` as `s` finishes the job.
Example 3
- Input
- target = "wolf", tray = "flow"
- Output
- 0
Each of `w`, `o`, `l` and `f` appears once in both trays, so no restamp is needed even though the tiles sit in a different order.
Example 4
- Input
- target = "zzzz", tray = "zabc"
- Output
- 3
`target` needs four `z` tiles and `tray` has one, so the `a`, `b` and `c` all get restamped as `z`.
Example 5
- Input
- target = "moon", tray = "noon"
- Output
- 1
`tray` holds two `n` tiles where `target` holds one, and holds no `m` where `target` holds one, so restamping one `n` as `m` is enough.
Constraints
- 1 <= target.length <= 5 * 10^4
- target.length == tray.length
- target and tray consist of lowercase English letters only.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def min_steps(target: str, tray: str) -> int:public int minSteps(String target, String tray)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 5 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- First Unique Character in a StringReal-world version: First Solo StopEasy
- Ransom NoteReal-world version: Spell It With TilesEasy
- Maximum Number of BalloonsReal-world version: Kettle Signs from the Tile TrayEasy
- Find Words That Can Be Formed by CharactersReal-world version: Signs Spellable From A Tile TrayEasy