Bulls and Cows

You write down a secret number and your friend makes a guess of the same length. The hint reports bulls, the digits in the guess that are in the correct position, and cows, the digits that appear in the secret but in a different position and that are not already bulls (each secret digit can be matched at most once). Given secret and guess, return the hint as "xAyB", where x is the number of bulls and y is the number of cows. Both strings may contain duplicate digits.

30:00

Bulls and Cows
medium
Free written solution
Topics
Companies

You write down a secret number and your friend makes a guess of the same length. The hint reports bulls, the digits in the guess that are in the correct position, and cows, the digits that appear in the secret but in a different position and that are not already bulls (each secret digit can be matched at most once). Given secret and guess, return the hint as "xAyB", where x is the number of bulls and y is the number of cows. Both strings may contain duplicate digits.

Example 1:
Input: {"secret":"1807","guess":"7810"}
Output: 1A3B
Constraints:
  • 1≤secret.length,guess.length≤10001 \leq \text{secret.length}, \text{guess.length} \leq 1000

  • secret.length == guess.length

  • secret and guess consist of digits only.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"secret":"1807","guess":"7810"}

Walk both strings together. Same digit in the same spot is a bull; otherwise park the digits in count[] so a later position can pair them up as cows.

bulls (A): 0

cows (B): 0

secret over guess, compared column by column

secret

1
8
0
7

guess

7
8
1
0

0

1

2

3

bull

cow (paired across positions)

dashed: unmatched, waiting in its bucket

count[digit]: above = secret copies waiting, below = guess copies waiting

0

0

1

0

2

0

3

0

4

0

5

0

6

0

7

0

8

0

9

0

A secret digit that finds guess copies waiting (count < 0) is a cow, and so is a guess digit that finds secret copies waiting (count > 0). Each copy is used once.

Variables
VariableValue
bulls0
cows0
DepthFunction Call
Stack empty
0/6