91. Hit and Near-Miss

A digit lock game has a hidden code secret, and a player tries a guess of the same length. After each try the host reports two numbers. A hit is a position where the guess has exactly the same digit as the secret. A near-miss is a guessed digit that is not a hit but still matches a digit of the secret sitting at a different, not-yet-used position; every digit of the secret can pair with at most one guessed digit, and hit positions can not be reused for near-misses.

Return the report as a string of the form "{hits}H{nearMisses}N", for example "2H1N".

Example 1

Input:
secret = "4071", guess = "4170"
Output:
"2H2N"
Explanation:

Positions 0 and 2 match (4 and 7), the remaining secret digits 0,1 and guess digits 1,0 pair up as two near-misses, so the report is 2H2N.

Example 2

Input:
secret = "1122", guess = "2211"
Output:
"0H4N"
Explanation:

No position matches, but all four digits can be paired up, giving 0H4N.

Constraints

1 ≤ secret.length = guess.length ≤ 5 * 105

secret and guess contain only the digits 0 to 9 (leading zeros are allowed).

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…