Skip to content

Cows and Bulls

LeWiz24 edited this page Aug 13, 2024 · 2 revisions

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q
    • What is the desired outcome?
      • To return the hint for a guess in the format "xAyB", where x is the number of bulls and y is the number of cows.
    • What input is provided?
      • Two strings, secret and guess.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Count the bulls in the first pass and the cows in the second pass using Counter.

1) Initialize `bulls` and `cows` to 0.
2) Initialize two `Counter` objects `secret_count` and `guess_count`.
3) First pass: Count the bulls and populate the `Counter` objects for non-bull characters.
4) Second pass: Count the cows by finding the minimum count of matching characters in `secret_count` and `guess_count`.
5) Return the result as a string in the format `"xAyB"`.

⚠️ Common Mistakes

  • Miscounting cows by not properly excluding bull positions.

I-mplement

from collections import Counter

def get_hint(secret, guess):
    bulls = 0
    cows = 0
    
    secret_count = Counter()
    guess_count = Counter()
    
    # First pass to count bulls
    for i in range(len(secret)):
        if secret[i] == guess[i]:
            bulls += 1
        else:
            secret_count[secret[i]] += 1
            guess_count[guess[i]] += 1
    
    # Second pass to count cows
    for char in guess_count:
        if char in secret_count:
            cows += min(secret_count[char], guess_count[char])
    
    return f"{bulls}A{cows}B"
Clone this wiki locally