Show problems as
Classic problem #299MediumHash TableStringCounting

Bulls and Cows

Real-world version: Keypad Feedback Code
Tracked in this browser only
Read Bulls and Cows on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A practice keypad holds a stored code and grades each attempt of the same length. Both are strings of digits, and digits may repeat in either of them.

The keypad grades an attempt with two counts:

  • locked: the number of positions where the attempt has the same digit as the code.
  • loose: how many of the attempt's remaining digits could be made to fit by moving them to another position. Formally, throw away the locked positions from both strings, and then for each digit value count how many times it survives in the attempt and how many times it survives in the code; the smaller of the two, summed over all ten digit values, is loose. Each surviving code digit can back at most one attempt digit.

Return the grade as the string "locked/loose", for example "2/1" for two locked and one loose. Both numbers are written in decimal with no padding.

Examples

Example 1

Input
code = "4506", attempt = "0456"
Output
"1/3"

Only the last position agrees, giving locked = 1. The leftover code digits are 4, 5, 0 and the leftover attempt digits are 0, 4, 5, which pair up completely, so loose = 3.

Example 2

Input
code = "2233", attempt = "3222"
Output
"1/2"

Position 1 agrees on the digit 2, so locked = 1. What is left of the code is 2, 3, 3 and what is left of the attempt is 3, 2, 2. One 2 and one 3 can be paired, and the attempt's spare 2 has no partner, so loose = 2.

Example 3

Input
code = "111", attempt = "123"
Output
"1/0"

Position 0 agrees, so locked = 1. The leftover code digits are 1, 1 and the leftover attempt digits are 2, 3, which share nothing, so loose = 0.

Example 4

Input
code = "77", attempt = "77"
Output
"2/0"

Both positions agree, so locked = 2 and nothing is left over.

Example 5

Input
code = "1234", attempt = "5678"
Output
"0/0"

No position agrees and no digit value appears in both strings.

Constraints

  • 1 <= code.length, attempt.length <= 1000
  • code.length == attempt.length
  • code and attempt consist of digits 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.

Python
def feedback(code: str, attempt: str) -> str:
Java
public String feedback(String code, String attempt)