All problems
0406MediumHash TableStringCounting

Restamps To Match The Tray

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1347Minimum Number of Steps to Make Two Strings Anagram

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def min_steps(target: str, tray: str) -> int:
Java
public int minSteps(String target, String tray)
September 7
Apply